如何在C++中生成随机数
How to generate random number in c++
#include<iostream>
using namespace std;
#include<stdlib.h>
int main()
{
cout<<rand();
}
当我运行这个程序时,它会生成随机数,比如41。当我再次运行这个程序时,它会生成相同的数字,即41。
但是我想在我们运行这个程序的时候一直生成不同的随机数。那么,请告诉我,如何才能做到?
此示例代码使用系统时间作为种子并使用 rand 函数生成随机数,因此每次 运行 此代码时,您都会得到不同的
随机数
#include <iostream>
#include <cstdlib>
#include <time.h>
using namespace std;
int main()
{
time_t t;
/*get the system time*/
time(&t);
/*transfer time_t variable to integer variable and send it to the srand function*/
srand((unsigned int) t);
/*Generating 10 random numbers continuous*/
for (int i = 0; i < 10; i++)
cout<<"The random number is "<<rand()<<endl;
cin.get();
return 0;
}
尝试初始化随机种子:
/* initialize random seed: */
srand (time(NULL));
#include<iostream>
using namespace std;
#include<stdlib.h>
int main()
{
cout<<rand();
}
当我运行这个程序时,它会生成随机数,比如41。当我再次运行这个程序时,它会生成相同的数字,即41。
但是我想在我们运行这个程序的时候一直生成不同的随机数。那么,请告诉我,如何才能做到?
此示例代码使用系统时间作为种子并使用 rand 函数生成随机数,因此每次 运行 此代码时,您都会得到不同的 随机数
#include <iostream>
#include <cstdlib>
#include <time.h>
using namespace std;
int main()
{
time_t t;
/*get the system time*/
time(&t);
/*transfer time_t variable to integer variable and send it to the srand function*/
srand((unsigned int) t);
/*Generating 10 random numbers continuous*/
for (int i = 0; i < 10; i++)
cout<<"The random number is "<<rand()<<endl;
cin.get();
return 0;
}
尝试初始化随机种子:
/* initialize random seed: */
srand (time(NULL));