1。)编写一个程序,生成10个随机数,范围为1到100.输出生成的最高随机数及其在列表中的位置。 样本输出:生成的十个随机数(1-100)是: 5 23 12 6 8 90 1 5 56 89 生成的最大数字为90,列表中的数字为6。
#include <iostream>
#include <cctype>
#include <cstdlib>
#include <ctime>
#include <windows.h>
using namespace std;
int main()
{
int rndNum, highest, position, ctr;
char tryagain;
do {
system("cls");
cout<<"The ten random numbers generated by the computer : "<<endl;
srand(time(0));
for(ctr=1, highest=0, position=0; ctr<=10; ctr++)
{
rndNum = rand() % 100 + 1;
rndNum = float(100*rand()/(RAND_MAX + 1.0));
if (rndNum > highest)
highest = rndNum;
cout<<rndNum<<"\t";
}
cout<<endl<<endl;
cout<<"The highest number generated is "<<highest<<endl;
cout<<"And it is number "<<position<<" on the list."<<endl;
cout<<endl<<endl;
cout<<"Press any key to try again and [X/x] to exit."<<endl;
cin>>tryagain;
tryagain = tolower(tryagain);
} while(tryagain != 'x');
system("pause");
return 0;
}
答案 0 :(得分:-1)
首先使用随机数生成器生成随机数的数组a[]
。然后声明两个变量big
:用于存储和比较最大数字和其他indexBig
:用于存储其索引。然后遍历数组并检查big
是否大于a[i]
。如果是,则将a[i]
分配给big
,将其i
分配给indexBig
,并将其与one
递增,以获得零索引的排名。这样做会检查数组的每个元素。最后,big
将包含最大数字,bigIndex
将包含最大数字的位置。
#include <iostream>
#include <cstdlib>
int main()
{
int a[10], big = 0, indexBig=1;
for(int i=0;i<10;i++)
{
a[i] = (rand()%100)+1;
std::cout<<a[i]<<" ";
if(a[i]>big)
{
big = a[i];
indexBig = i+1;
}
}
std::cout<<big<<" "<<indexBig;
}