C ++,二十数不随机? [英] C++, twenty numbers not random?

查看:112
本文介绍了C ++,二十数不随机?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我的C ++号码不是随机的?

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?


推荐答案

每次你需要调用rand一个随机数。现在你已经生成了一个随机数,然后增加并打印20次,这样你就可以得到20个连续的数字。

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.

尝试一下如

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.

这篇关于C ++,二十数不随机?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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