srand(time(0)) not making random numbers?

安稳与你 提交于 2019-12-13 09:50:42

问题


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?
}

回答1:


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?
}

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.




回答2:


You must call rand() each loop iteration.

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

What was happening before was that you were calling rand() twice, one for r1 and once for r3, and then simply printing the result 5 times.



来源:https://stackoverflow.com/questions/22749167/srandtime0-not-making-random-numbers

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!