我希望我的程序能够生成500个10到65范围内的随机数。请问如何实现?
目前,我的程序会生成0到74之间的随机数。同时,我发现最高值和最低值显示的并不是生成的随机数,而是随机数的范围。以下是我的代码:
目前,我的程序会生成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;
}
std::uniform_int_distribution<int> distribution(10, 65);
可能会有所帮助。 - Jarod42