我正在尝试编写一个生成并输出x随机整数num的程序 - 尚未使用数组或更高级别的C ++(我在循环中,例如while,for等)。
num是20到50之间的随机数,x是10到15之间的随机数。
我还想计算并显示这些数字的最小,最大,总和和平均值。我希望我的Sample测试输出X个随机整数数(在我失败的样本运行的情况下,它应该是12随机整数)。
如何确保它显示所有x个整数,并且它在此列表中显示的每个整数是随机且唯一的,而不是重复相同的随机数(在我底部的失败样本运行中,此整数为37 ,但我希望它是12个不同的唯一数字)?
/*
OUTPUT SHOULD BE:
Generating 11 random numbers (11 is a random number between 10 to 15)...
...11 Random Numbers between 20 to 50: 26, 23, 48, 32, 44, 21, 32, 20, 49, 48, 34
Largest = 49
Smallest = 21
Sum = 377
Average = 377 / 11 = 34.3
*/
#include <stdlib.h>
#include <time.h>
#include <iostream>
using namespace std;
int main(void)
{
srand(time(NULL));
{
while (true){
int sum = 0;
int x = 10+rand()%6;
int denom = x+1;
int num = 20+rand()%31;
int largest;
int smallest;
cout<<"Generating " << x << " random numbers (" << x << " is between 10 and 15)... \n";
cout << "..." << x << " Random Numbers between 20 to 50: ";
cout << num << endl;
while(x >= 0)
{
largest = num;
smallest = num;
sum = sum + num;
x--;
}
int average = sum / denom;
cout << "Largest = " << largest << endl;
cout << "Smallest = " << smallest << endl;
cout << "Sum = " << sum << endl;
cout << "Average = " << average << endl;
break;
}
return 0;
}
}
/*
SAMPLE RUNS
==========
Generating 12 random numbers (12 is between 10 and 15)...
...12 Random Numbers between 20 to 50: 37
Largest = 37
Smallest = 37
Sum = 481
Average = 37
Process returned 0 (0x0) execution time : 0.159 s
Press any key to continue.
*/
答案 0 :(得分:1)
仅使用一个循环。应在此循环中生成随机数num
。
它应该是while (x > 0){... x--;}
所以例如x == 1
然后循环运行一次。您还可以使用更容易理解的for
循环。
denom
只是保存x
的值。因此,它应该是x
,而不是x+1
largest
和smallest
的值应在循环开始之前初始化。然后你必须测试值。
我使用零来初始化largest
和非常大的值RAND_MAX
来初始化smallest
。
int main()
{
srand((unsigned int)time(NULL));
int largest = 0;
int smallest = RAND_MAX;
int sum = 0;
int x = 10 + rand() % 6;
int denom = x;
cout << "x = " << x << endl;
while (x > 0)
{
int num = 20 + rand() % 31;
cout << "num = " << num << endl;
if(num > largest)
largest = num;
if(num < smallest)
smallest = num;
sum += num;
x--;
}
cout << "Largest = " << largest << endl;
cout << "Smallest = " << smallest << endl;
cout << "Sum = " << sum << endl;
cout << "Average = " << sum / denom << endl;
return 0;
}