C++, twenty numbers not random? [closed]

2019-01-27 12:33发布

问题:

Why are my C++ numbers not random?

#include <iostream>
#include <cstdlib>
using namespace std;


int main()
{
    int randomNumber = rand() % 100;


    for (randomNumber = 0; randomNumber < 20; randomNumber++)
    {

        cout << randomNumber << endl;
    }
    return 0;
}

//Why are my 20 numbers not random?

回答1:

You need to call rand() each time you want a random number. As you have it now you're generating one random number, then incrementing it and printing it out 20 times so you're going to get 20 sequential numbers.

Try something like

srand(time(NULL)); // Seeding the random number generator

for(int i=0; i<20; ++i)
{
    cout << (rand() % 100) << endl;
}

The seeding of the random number generator is important, without that you would generate the same numbers every time you ran the program.



回答2:

You're assigning randomNumber a random value, and then overwriting it with the numbers 0 through 19 in your for loop. Before your loop, you have a random number.



回答3:

You need to properly seed your random number generator, and then you need to repeatedly call rand() to get a new random number.

For example:

srand(time(NULL));
for (int randomNumber = 0; randomNumber < 20; randomNumber++) 
{ 

    cout << (rand() % 100) << endl; 
} 


回答4:

You need to use time() function as a seed in srand() and then use rand().

srand(time(NULL));

By the way you are not printing the rand() result, use this after the srand call:

for (int i= 0; i < 20; i++)
{
    int randomNumber = rand() % 100;
    cout << randomNumber << endl;
}


回答5:

#include <iostream>
#include <cstdlib>
using namespace std;

int main()
{
    for (int i = 0; i < 20; i++)
    {
        int randomnumber = rand() % 100;
        cout << randomNumber << endl;
    }
    return 0;
}

P.S. I hope this is a joke :(



标签: c++ random