问题描述
限时送ChatGPT账号..我需要在 C++ 中生成一个 4 位随机数
I need to generate a 4 digit random number in C++
我使用了以下代码
#include<time.h>
int number;
number=rand()%1000;
srand ( time(NULL) );
但它没有给出一个总的随机数
but its doesn't gives a total random number
推荐答案
number = rand() % 9000 + 1000;
有 9000 个四位数,对吧?从 1000 到 9999.rand()
将返回一个从 0 到 RAND_MAX
的随机数.rand() % 9000
将从 0 到 8999 而 rand() % 9000 + 1000;
将从 1000 到 9999 .一般来说,当你想要一个从 a 到 b 的随机数时,公式是
There are 9000 four-digit numbers, right? Starting from 1000 till 9999. rand()
will return a random number from 0 to RAND_MAX
. rand() % 9000
will 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
rand() % (b - a + 1) + a
另请注意,srand()
应该只调用一次,并且应该在任何 rand()
之前调用.
Also note that srand()
should be called only once and before any rand()
.
如果您确实认为 0 到 999 之间的数字是四位数字",那么在这种情况下只需使用 rand() % 10000
.我不认为它们是,但我涵盖了所有基础,以防万一.
If you do consider the numbers between 0 an 999 inclusive to be "four digit numbers", simply use rand() % 10000
in that case. I don't consider them to be but I'm covering all bases, just in case.
HTH
这篇关于C++ 生成一个 4 位随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论