[英]How can I generate random numbers between 1 and a number input by the user?
How do I create a program that generates ten random numbers from 1 -> RAND_MAX
?如何创建一个从 1 ->
RAND_MAX
生成十个随机数的程序?
RAND_MAX
must be a number input by the user. RAND_MAX
必须是用户输入的数字。
#include <iostream>
#include <stdlib.h>
int main()
{
using namespace std;
int x;
int y;
Random:
{
x = rand();
cout << x << endl;
}
y = y + 1;
if (y == 10) {
return 0;
}
goto Random;
}
Disclaimer: rand
is a quick and dirty way to generate random numbers, as it may not generate numbers perfectly uniformly and you'll run into some issues if RAND_MAX
(the upper limit for rand
) is defined to be smaller than your target range.免责声明:
rand
是一种生成随机数的快速而肮脏的方法,因为它可能无法完全均匀地生成数字,并且如果RAND_MAX
( rand
的上限)被定义为小于您的目标范围,您会遇到一些问题。 In modern C++ it would be better to use the <random>
header, as per the question Generate random numbers uniformly over an entire range .在现代 C++ 中,最好使用
<random>
标头,根据问题Generate random numbers uniformly over an entire range 。
Something like:就像是:
int main()
{
int randMax;
cin >> randMax;
for (int y = 0; y < 10; y++)
{
int x = rand() % randMax; // Range = [0, randMax)
cout << x+1 << endl; // Range = [1, randMax]
}
}
Oh, and do try to avoid goto
(at least in my opinion).哦,一定要尽量避免
goto
(至少在我看来)。 Here are two questions about it.这里有 两个关于它的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.