生成随机数并在控制台上打印它们(c++)
visual studio - generating random numbers and printing them on the console (C++)
我正在研究一个简单的想法,生成随机数(从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))
将为您完成此操作,正如其他人所解释的那样。
- 如何循环打印顶点结构
- 为什么在popback()操作之后,它仍然打印完整的矢量
- 如何在c++中打印目录
- 有一个打印语句的函数是一种糟糕的编程实践吗
- 在线编译器中的分段C++没有打印消息
- 在C++中打印指向不同基元数据类型的指针的内存地址
- 这个指针和内存代码打印是什么?我不知道是打印垃圾还是如何打印我需要的值
- 如何将结构插入到集合中并打印集合的成员
- 在循环C++中指定字符串之后,不会打印该字符串
- 以螺旋方式打印矩阵的程序.(工作不好)
- 从控制台中删除最后打印的元素
- 如何使用Crypto++并为RSA返回可打印的字节/字符数组
- 如何仅使用对象名称打印特定于对象的成员
- 回溯C++不打印函数,因此文件
- 在一定长度后从数组中打印时缺少整数
- 为什么这个 c++ 代码打印出长度 5,当我打印出字符串时,程序会自动终止?
- 在gem5中打印文件中的所有cache_blocks
- 打印数字图案
- Log4cpp:以UTC/GMT时区打印日期
- 如何使用gdb制作一个可以漂亮地打印每个对象的C++函数