【问题标题】:srand(time(0)) not making random numbers?srand(time(0)) 不生成随机数?
【发布时间】: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)) ?
  • 您没有更改循环内的值 r1r3
  • @NeilKirk 因为 c++ 提供。 std::default_random_engine 和其他复杂的类。
  • 我认为您对赋值运算符和表达式的工作方式感到困惑。您没有将表达式分配或绑定到变量,而是将表达式的 result 分配给它。
  • @deeiip 那是 C++11,他可能没有使用。

标签: c++ random srand


【解决方案1】:

您需要将对 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

【讨论】:

【解决方案2】:

您必须在每次循环迭代时调用rand()

for (int i = 0; i <5; i++)
{
    cout << 2 + rand() % (11 - 2) << endl;    
    cout << rand() << endl;          
}

之前发生的情况是您调用了两次rand(),一次调用r1,一次调用r3,然后简单地打印了5次结果。

【讨论】:

    猜你喜欢
    • 2011-06-11
    • 2020-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多