【发布时间】:2014-03-30 20:08:01
【问题描述】:
这是代码,但输出不是随机的?也许是因为程序运行时它与所有循环的时间相同?
#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?
}
【问题讨论】:
-
为什么在 c++ 中使用 srand(time(0)) ?
-
您没有更改循环内的值
r1和r3。 -
@NeilKirk 因为 c++ 提供。 std::default_random_engine 和其他复杂的类。
-
我认为您对赋值运算符和表达式的工作方式感到困惑。您没有将表达式分配或绑定到变量,而是将表达式的 result 分配给它。
-
@deeiip 那是 C++11,他可能没有使用。