[英]I don't know how to locate the position of the highest random number
1.) Write a program that generates ten random numbers in the range of 1 to 100. Output the highest random number generated and its position in the list. 1.) 编写一个程序,生成 1 到 100 范围内的十个随机数。输出生成的最高随机数及其在列表中的位置。 Sample Output: The ten random numbers (1-100) generated are: 5 23 12 6 8 90 1 5 56 89 The highest number generated is 90, and it is number 6 on the list.
样本输出:生成的十个随机数(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;
}
First generate the array a[]
of random numbers using a random number generator.首先使用随机数生成器生成随机数数组
a[]
。 Then declare two variables, big
: for storing and comparing largest number and other indexBig
: is for storing its index.然后声明两个变量,
big
:用于存储和比较最大数,其他indexBig
:用于存储其索引。 Then loop through the array and check if big
is greater than a[i]
.然后遍历数组并检查
big
是否大于a[i]
。 If yes then assign a[i]
to big
and its index i
to indexBig
,and increment it with one
to get the position from zero index.如果是,则将
a[i]
分配给big
并将其索引i
分配给indexBig
,并将其加one
以从零索引获取位置。 Do this check for every elements of array.对数组的每个元素执行此检查。 At last,
big
will contain the largest number and bigIndex
will contain the position of largest number.最后,
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.