srand(time(0)) 不生成随机数? [英] srand(time(0)) not making random numbers?

查看:54
本文介绍了srand(time(0)) 不生成随机数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是代码,但输出不是随机出现的?也许是因为程序运行时它与所有循环的时间相同?

Here is the code, but the outputs aren't coming out random? Maybe cause when the program runs it has the same time as all the loops?

#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() 的调用移动到您的循环中:

You need to move your calls to rand() to inside your loop:

#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.

That said: since you're writing C++, you really want to use the new random number generation classes added in C++ 11 rather than using srand/rand at all.

这篇关于srand(time(0)) 不生成随机数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆