这里是代码,但是输出不是随机输出的吗?可能是因为程序在运行时与所有循环都具有相同的时间?
#include <iostream>
using namespace std;
#include <string>
#include <cmath>
#include <ctime>
#include <cstdlib>
int main()
{
long int x = 0;
bool repeat = true;
srand( time(0));
int r1 = 2 + rand() % (11 - 2); //has a range of 2-10
int r3 = rand();
for (int i = 0; i <5; i++)
{
cout << r1 << endl; //loops 5 times but the numbers are all the same
cout << r3 << endl; // is it cause when the program is run all the times are
} // the same?
}
您需要将对rand()
的呼叫转移到循环内:
#include <iostream>
using namespace std;
#include <string>
#include <cmath>
#include <ctime>
#include <cstdlib>
int main()
{
long int x = 0;
bool repeat = true;
srand( time(0));
for (int i = 0; i <5; i++)
{
int r1 = 2 + rand() % (11 - 2); //has a range of 2-10
int r3 = rand();
cout << r1 << endl; //loops 5 times but the numbers are all the same
cout << r3 << endl; // is it cause when the program is run all the times are
} // the same?
}
就是说:由于您正在编写C ++,因此您确实想使用C ++ 11中添加的新随机数生成类,而不是完全使用srand
/ rand
。
您必须在每个循环迭代中调用rand()
。
for (int i = 0; i <5; i++)
{
cout << 2 + rand() % (11 - 2) << endl;
cout << rand() << endl;
}
之前发生的事情是您两次调用rand()
,一次调用r1
,一次调用r3
,然后简单地将结果打印5次。