继承代码,但输出是否随机出现?也许会导致程序运行时与所有循环时间相同?
#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?
}
答案 0 :(得分:4)
您需要将调用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
。
答案 1 :(得分:1)
您必须每次循环迭代调用rand()
。
for (int i = 0; i <5; i++)
{
cout << 2 + rand() % (11 - 2) << endl;
cout << rand() << endl;
}
以前发生的事情是您拨打rand()
两次,一次拨打r1
,一次拨打r3
,然后只打印五次结果。