C++ 生成一个 4 位随机数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4067135/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 14:28:37  来源:igfitidea点击:

C++ Generating a 4 digit random number

c++visual-c++

提问by Sudantha

I need to generate a 4 digit random number in C++

我需要在 C++ 中生成一个 4 位随机数

I used the following code

我使用了以下代码

#include<time.h>

int number;

number=rand()%1000;
srand ( time(NULL) );

but its doesn't gives a total random number

但它没有给出一个总的随机数

回答by Armen Tsirunyan

number = rand() % 9000 + 1000;

There are 9000 four-digit numbers, right? Starting from 1000 till 9999. rand()will return a random number from 0 to RAND_MAX. rand() % 9000will be from 0 to 8999 and rand() % 9000 + 1000;will be from 1000 to 9999 . In general when you want a random number from a to b inclusive the formula is

有 9000 个四位数,对吧?从 1000 到 9999.rand()将返回一个从 0 到 的随机数RAND_MAXrand() % 9000将从 0 到 8999 ,rand() % 9000 + 1000;从 1000 到 9999 。一般来说,当你想要一个从 a 到 b 的随机数时,公式是

rand() % (b - a + 1) + a

Also note that srand()should be called only once and before any rand().

还要注意,srand()应该只调用一次并且在 any 之前调用rand()

If you doconsider the numbers between 0 an 999 inclusive to be "four digit numbers", simply use rand() % 10000in that case. I don't consider them to be but I'm covering all bases, just in case.

如果您确实认为 0 到 999 之间的数字是“四位数字”,请rand() % 10000在这种情况下使用。我不认为它们是,但我涵盖了所有基础,以防万一。

HTH

HTH

回答by dalle

Remember to call srandonly once.

记住srand只调用一次。

Take a look at Boost.Random, if you don't like the distribution of rand.

如果您不喜欢.Random的分布,请查看Boost.Randomrand

// produces randomness out of thin air
boost::mt19937 rng;

// distribution that maps to 1000..9999
boost::uniform_int<> fourdigits(1000,9999);

// glues randomness with mapping
boost::variate_generator<boost::mt19937&, boost::uniform_int<> > die(rng, fourdigits);

// simulate rolling a die
int x = die();

回答by log0

You must seed your random generator srandbeforecalling rand()

您必须srand调用之前为您的随机生成器播种rand()

#include<time.h>

srand( time(NULL) );
int number = rand() % 10000; // number between 0 and 9999