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

编程入门 行业动态 更新时间:2024-10-09 01:13:35
本文介绍了C++ 生成一个 4 位随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送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:关键词]

本文发布于:2023-04-27 15:49:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1157067.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:随机数

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!