【发布时间】:2016-10-24 23:19:23
【问题描述】:
我查看了此处提出的其他问题,但找不到我需要的内容。
我有这个问题;
编写一个程序,生成 0-49 范围内的 1000 个随机整数。它应该计算并报告有多少在 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++ 很陌生,所以有人能解释一下如何让它循环吗?我错过了一些非常明显的东西吗?
【问题讨论】:
-
您可以使用更长的变量名,朋友,因此您可以将其命名为 number_of_results_twentyfive_and_higher 而不是“z”……这将使您的代码在 10 个月后更易于阅读。
-
投票结束是愚蠢的错字。大括号太多,在循环内返回。
-
rand() % 49 + 1生成 1-49 范围内的数字。要生成 0-49 范围内的数字,请改用rand() % 50。