生成随机数并在控制台上打印它们(c++)

visual studio - generating random numbers and printing them on the console (C++)

本文关键字:c++ 打印 随机数 控制台      更新时间:2023-10-16

我正在研究一个简单的想法,生成随机数(从1到100),并使用c++在控制台上打印它们,但问题是,每次我运行程序时,它每次都会生成完全相同的数字,它是随机的,单个数字不重复,但每次都是相同的随机数顺序!

这是我的代码

// DigitDisplayer.cpp : Defines the entry point for the console application.
//
#include "stdafx.h" 
#include <iostream>
#include <cstdlib>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
    int max = 100;
    int min = 1;
    int range = (max - min) + 1;
int randnum;
bool nums[100];
for(int j = 0; j < sizeof(nums); j++)
{
    nums[j] = false;
}
for(int i = 0; i < range; i++)
{
    int randnum = (rand() % range) + 1;
    if(nums[randnum] == false){
        nums[randnum] = true;
        cout<< randnum << "nn";
    }
    else {
        int randnum = (rand() % range) + 1;
    }
}
cout<< "DONE!!!nn";
system ("pause");
}

谢谢

c++中的随机数生成器实际上是一个伪随机序列生成器,它从给定的种子开始。

这样做有两个原因:

  • 很难在所有实现c++库的机器上找到真正的随机源。

  • 显然需要一个生成可重复序列的随机数生成器(例如,如果您的单元测试依赖于随机数,您希望测试是可重复的-并接收相同的"随机数")。

这就是为什么你有一个srand函数,它为随机数的生成提供了一个"种子"。

如果您不调用srand或使用相同的值调用它,则您的"随机"序列将始终相同。

如果你用不同的种子调用它,结果序列将是唯一的(在实践中,它可能有一个模式或可预测的-这取决于实现)。

您必须使用srand来播种rand函数,否则它总是返回同一组数字。cstdlib

定义的time()函数

检查:

// DigitDisplayer.cpp : Defines the entry point for the console application.
//
#include "stdafx.h" 
#include <iostream>
#include <cstdlib>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
    int max = 100;
    int min = 1;
    int range = (max - min) + 1;
    int randnum;
    bool nums[100];
     srand (time(NULL));
for(int j = 0; j < sizeof(nums); j++)
{
    nums[j] = false;
}
for(int i = 0; i < range; i++)
{
    int randnum = (rand() % range) + 1;
    if(nums[randnum] == false){
        nums[randnum] = true;
        cout<< randnum << "nn";
    }
    else {
        int randnum = (rand() % range) + 1;
    }
}
cout<< "DONE!!!nn";
system ("pause");
}

您需要为随机数生成器设置种子。查看srand()了解如何做到这一点。

你通常要做的就是在使用rand()之前调用一次srand()。注意,每次运行程序时都应该使用不同的值调用srand()

例如,使用time()来播种是最简单的方法:

int main()
{
     srand(time(NULL));
     .....
     rand();
     .....
}

计算机不能生成随机数。相反,他们使用一种算法来生成一系列数字,这些数字近似于随机数的行为方式。这些算法被称为伪随机数生成器(PNRGs)。在我所知道的每一种情况下,这些pnrg都可以"播种"一个数字,这决定了伪随机数序列将从哪里开始。如果您希望每次都得到不同的结果,则需要使用不同的数字来播种PNRG。对于大多数用途,系统计时器足以生成有效的随机数序列。srand(time(NULL))将为您完成此操作,正如其他人所解释的那样。

顺便说一下:C中内置的随机数生成器非常糟糕。除了最不经意的场合,它并不适合在所有场合使用;如果你想要一个像样的随机数来源,可以考虑使用像Mersenne Twister这样的东西。在高度敏感的情况下(如在线赌博等),定时播种也会出现问题。