【发布时间】:2015-11-27 14:58:51
【问题描述】:
我希望我的程序生成 500 个随机数,范围为 10 到 65。我该怎么做?
目前,我的程序生成 0 到 74 个随机数。
而且,似乎我的最高和最低值不是读取随机生成的数字而是读取它的范围。
这是我的代码:
#include<iostream>
#include<exception>
#include<stdlib.h>
using namespace std;
int main(){
int year;
int nextLine = 20;
int highestValue = 0;
int lowestValue = 0;
int ages[500];
int range = 65;
cout << "Enter year today: ";
cin >> year;
srand(year);
cout << "The ages are: \n";
for (int i = 0; i < 500; i++){
ages[i] = rand() % 65 + 10;
cout << ages[i] << " ";
if (i + 1 == nextLine){
cout << "\n";
nextLine += 20;
}
}
for (int j = 0; j < 500; j++){
if (ages[j] > highestValue)
highestValue = ages[j];
if (ages[j] < lowestValue)
lowestValue = ages[j];
}
cout << "\nRange(HV-LV): " << highestValue << " - " << lowestValue << " = " << highestValue - lowestValue;
system("pause>0");
return 0;
}
编辑: 这是一个包含范围的工作代码。 :)
#include<iostream>
#include<exception>
#include<algorithm>
using namespace std;
int main(){
int year;
int nextLine = 20;
int highestValue;
int ages[500];
int lowestValue;
int range = 65;
cout << "Enter year today: ";
cin >> year;
srand(year);
cout << "The ages are: \n";
for (int i = 0; i < 500; i++){
ages[i] = rand() % 56;
ages[i] += 10;
cout << ages[i] << " ";
if (i + 1 == nextLine){
cout << "\n";
nextLine += 20;
}
}
highestValue = *max_element(ages, ages + 500);
lowestValue = *min_element(ages, ages + 500);
cout << "\nRange(HV-LV): " << highestValue << " - " << lowestValue << " = " << highestValue - lowestValue;
system("pause>0");
return 0;
}
【问题讨论】:
-
在 C++11 中,
std::uniform_int_distribution<int> distribution(10,65);可能会有所帮助。