为什么每次运行程序时,我的"随机"生成的数字都在增加?

Why are my 'randomly' generated numbers are increasing every time I run the program?

本文关键字:数字 增加 随机 程序 运行 为什么 我的      更新时间:2023-10-16

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

例如,如果我使用下面提供的代码,运行并关闭程序10次,输出将是:
42
52
72
78
85
92
12 (it has reset)
32
48  

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

#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;
}

但是,如果我使用这段代码:

#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;
}

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

31
10
81
66
74
14
6
97
39
23 

它们以随机数量随机增加和减少。这里有什么问题吗?

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

一个更好的解决方案是使用std::uniform_int_distribution代替rand

另一个潜在的问题是rand的一些实现可能与某些模块交互不良。出于这个原因,您可能需要考虑这样做:

 int v = ((double)rand() / (double)RAND_MAX) * 100 + 1;

仍然不理想,但很容易。