为什么每次运行程序时我的“随机"生成的数字都会增加? [英] Why are my 'randomly' generated numbers are increasing every time I run the program?

查看:67
本文介绍了为什么每次运行程序时我的“随机"生成的数字都会增加?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过使用 srand()rand() 来获得随机生成的数字,但没有 avale:每次我运行程序时,它都会增加一个一定数量的数字.但是如果我使用 for 语句,则看不到任何模式.

I'm trying to get randomly generated numbers by using srand() and rand() but with no avale: every time I run the program it increases by a certain amount of numbers. But if I use a for statement, no pattern can be seen.

例如,如果我使用下面提供的代码并运行并关闭程序 10 次,输出将是:

For example, if I use the code provided below and run and close the program 10 times, the output will be:

42
52
72
78
85
92
12 (it has reset)
32
48  

注意:我注意到一件奇怪的事情,当我取消聚焦或最小化 Visual Studio 并关闭命令提示符时,下次运行程序时,数字会增加增加了 20 多个,但是,如果我不聚焦或最小化 Visual Studio,这个数字会增加 1-5 多一点.这是为什么?

Note: one strange thing I noticed about this that when I unfocus or minimize Visual Studio and close the Command Prompt, the next time I run the program the number increases by more than 20, but, if I don't unfocus or minimze Visual Studio the number increases by just little over 1-5. Why's that?

#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

int main()
{
    srand (time(NULL));

    int random_number = rand () % 100 + 1;
    cout << "Random number: " << random_number << endl;

    return 0;
}

但是,如果我使用此代码:

But, if I use this code:

#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

int main()
{
    srand (time(NULL));

    for (int i = 0; i < 10; i++) {
        int random_number = rand () % 100 + 1;
        cout << "Random number: " << random_number << endl;
    }

    return  0;
}

数字没有清晰的模式,我得到了输出:

the numbers don't have a clear pattern and I get the output:

31
10
81
66
74
14
6
97
39
23 

它们按随机数量随机增加和减少.这里似乎有什么问题?

They increase and decrease randomly by random amounts. What seems to be the problem here?

推荐答案

某些版本的 rand 返回的前几个随机数(看看你微软)与它们开始的种子高度相关,只是由于使用了随机数生成器公式.由于运行之间的时间变化不大,随机数也没有变化.如果您丢弃返回的前几个随机数,您可以获得更好的结果.

The first few random numbers returned by some versions of rand (looking at you Microsoft) are highly correlated to the seed they start with, just due to the random number generator formula being used. Since the time isn't changing much between runs, neither do the random numbers. If you throw away the first few random numbers that get returned you can get much better results.

更好的解决方案是使用 std::uniform_int_distribution 而不是 rand.

A better solution is to use std::uniform_int_distribution instead of rand.

这篇关于为什么每次运行程序时我的“随机"生成的数字都会增加?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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