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

2019-01-27 12:13发布

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?

标签: c++ random
5条回答
我想做一个坏孩纸
2楼-- · 2019-01-27 12:28

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;
}
查看更多
Root(大扎)
3楼-- · 2019-01-27 12:32

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楼-- · 2019-01-27 12:34

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.

查看更多
祖国的老花朵
5楼-- · 2019-01-27 12:35
#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 :(

查看更多
迷人小祖宗
6楼-- · 2019-01-27 12:48

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.

查看更多
登录 后发表回答