编写程序生成1000个0-49范围内的随机整数.(c++)
Write a program that will generate 1000 random integers in the range 0-49. (C++)
我已经看了这里问的其他问题,但不能找到我需要的。
我有这个问题;
编写程序生成1000个0-49范围内的随机整数。它应该计数并报告在0-24范围内有多少,在25-49范围内有多少。
这是目前为止我写的;
#include<iostream>
#include<ctime> //For time()
#include<cstdlib> //For rand() and srand()
using namespace std;
int main()
{
int x;
int counter = 0;
int y = 0;
int z = 0;
srand(time(NULL));
for (counter = 0; counter < 1000; counter++) {
{
x = rand() % 49 + 1;
if (x >= 0 && x <= 24)
{
y++;
}
else if (x > 24 && x <= 49)
{
z++;
}
}
cout << "Number of numbers between 0-24: " << y << endl;
cout << "Number of numbers between 25-49: " << z << endl;
system("pause");
return 0;
}
}
它循环一次,但我不明白如何让它循环一遍又一遍,直到1000个数字已经生成和分类。
我对c++很陌生,所以有人能解释一下如何让这个循环吗?我错过了什么非常明显的东西吗?
你在for
循环中有太多的花括号。正因为如此,你的return
和cout
在for
循环中发生。它得到一个数字,打印出来,然后在它返回之前返回。试试这个:
#include<iostream>
#include<ctime> //For time()
#include<cstdlib> //For rand() and srand()
using namespace std;
int main()
{
srand(time(NULL));
for (counter = 0; counter < 1000; counter++)
{
int x; //See Note #3 Below
int counter = 0;
int y = 0;
int z = 0;
x = rand() % 50; //See Note #1 Below
if (x < 25) //See Note #2 Below
{
y++;
}
else
{
z++;
}
}
cout << "Number of numbers between 0-24: " << y << endl;
cout << "Number of numbers between 25-49: " << z << endl;
system("pause");
return 0;
}
关于代码的3个注意事项:
- 你的随机数生成器只得到数字1-49,而不是0-49。
- 你真的不需要这样构造if语句。你所要做的就是说,"如果小于25,把它放在一个桶里,否则,把它放在另一个桶里。"
- 你可能想在变量被使用的范围内声明变量。在本例中,是您的
for
循环。
相关文章:
- 生成线性随机整数C++
- 如何生成 0 到 0x7FFFFFFF 的随机整数?
- 生成随机整数
- C++:随机数列表:x 个随机整数
- C++带有权重的随机非重复整数
- 列出小于 10 的不同随机整数
- 在 c++ 中生成随机整数
- C++随机函数给出的相同整数是输出的两倍
- 取消随机排列整数/字符数组
- 随机选择 2 个不在范围内的整数
- 我将如何防止整数在随机发生器中多次生成
- C++ 通过 range for 循环将整数输入到矢量中;随机 0
- 随机整数仍在生成低于或高于范围的数字?
- C++,为什么我不能使用两个默认随机引擎生成独立的随机整数样本
- 在 C++ 中使用 10 个随机整数的数组进行气泡排序不起作用
- C++ 如何生成 10,000 个 UNIQUE 随机整数以存储在 BST 中?
- 如何将唯一的随机整数插入链表中
- 伪随机整数
- 生成伪随机16位整数
- 使用boost::random库获取整数随机值而不是实数