c++随机数加随机种子(用时间为随机种子)随机每次运行都不同

时间:2025-03-30 07:59:15

**

srand()

**
功能:初始化随机数发生器
用法:srand(unsigned int seed)
需要头文件:
返回值:void无返回值

rand() 产生的随机数在每次运行的时候都是与上一次相同的。若要不同, 用函数 srand() 初始化它。可以利用 srand((unsigned int)(time(NULL)) 的方法,产生不同的随机数种子,因为每一次运行程序的时间是不同的。

实例:

#include <iostream>
#include <>
#include <>
int main()
{
    srand((unsigned)time(NULL));
    for (int i = 0; i < 10; i++)
    {
        std::cout << rand()<<"\n";
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11