简体   繁体   中英

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. 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.

#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. Then declare two variables, big : for storing and comparing largest number and other indexBig : is for storing its index. Then loop through the array and check if big is greater than 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. 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.

#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;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM