如何在1和用户输入的数字之间生成随机数?
How can I generate random numbers between 1 and a number input by the user?
如何创建一个程序,从1 ->RAND_MAX
?
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;
}
免责声明: rand
是一种快速而肮脏的方式来生成随机数,因为它可能不会完全均匀地生成数字,如果RAND_MAX
(rand
的上限)被定义为小于目标范围,您将遇到一些问题。在现代c++中,最好使用<random>
头,如问题在整个范围内均匀地生成随机数。
类似:
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]
}
}
哦,尽量避免goto
(至少在我看来)。这里有两个关于它的问题
相关文章:
- 在数字之间插入 + 或 - 符号以使其等于整数
- 将向量之间的数字放在另一个向量之间<vector>>如果两个数字的差值为 1
- 获取 2 个数字之间的差异百分比
- 两个有符号数字之间的距离
- 无法理解代码背后的逻辑,这是在两个给定数字之间生成素数的优化问题
- C++:这两种将数字写入矩阵的方式之间是否存在显着的速度差异?
- 如何从txt文件c++中提取括号之间的数字
- 正则表达式匹配字符串之间的数字
- C++显示两个区间之间的数字的程序检查一个数字是否可以表示为两个素数的总和
- 数字之间的比较
- 在没有比较运算符的情况下查找 2 个数字之间的最小值
- 在[a,b]间隔之间找到相同的数字
- 不理解连续数字之间的空格代码
- 如果 2 个数字之间的差值在 1 到 100 之间,则应运行 if 语句
- 第一个和第二个数字之间能被 4 和 6 整除的所有整数的总和
- 0 和 n 之间有多少个数字满足按位属性 i&y==i?
- 2 个给定数字之间的双精度密度
- 三个数字之间的 C++ 相加两个更高的数字,没有循环和数组
- 我如何生成2D数组,在行和列之间具有不同的数字
- 给定n个数字,编写一个例程,以在4个连续数字之间找到最大的数字