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

2019-10-05 05:13发布

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

标签: c++ random srand
2条回答
一纸荒年 Trace。
2楼-- · 2019-10-05 06:02

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.

查看更多
不美不萌又怎样
3楼-- · 2019-10-05 06:03

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.

查看更多
登录 后发表回答