如何在数组中找到最大的数字并以c ++显示它

时间:2014-09-19 18:41:18

标签: c++ arrays

所以我需要在数组中输入数字并找到并显示最大的数字,我不确定我在那里的循环是否是最好的方法。此外,我并不积极如何设置它,我已尽最大努力完成任何输入将非常感谢!

#include <iostream>
#include <iomanip>
#include <cstdlib>
using namespace std;



int main()
{
// initialize the CONSTANTS
const int SENTINEL = -1;

// initialize the variables
int num1 = 0;
int i;
int sum = 0;
int n;
int a[10];
int largest;
float avg;

/***************************************BEGIN*********************************************/

// Title largest of three revised
cout << setw(25) << "Largest Of Three Revised Program" << "\n";


// prompt user for how many numbers they want to input for size of array with -1 to QUIT
cout << setw(25) << "*********************************************" << endl;
cout << setw(25) << "Enter how many elements you want " << SENTINEL << " to quit " << endl;
cout << setw(25) << "*********************************************" << endl;
while (num1 != SENTINEL)
{
   // user inputs a number for array size
   cin >> setw(45) >> n;

      // if number is larger then 10 array is automatically set to 10
      if (n>10)
         n=10;

      // prompts users for numbers to fill the array
      cout << setw(45) << "Enter the "<< n <<" array elements\n";

      // clear screen
      //system("cls");

         // puts user input numbers into the array while incrementing the count
         for (i=0;i<n;i++)
         cin >> setw(45) >> a[i];

         // finds the largest number
         largest = a[0];
            for(i=1;i<n;i++)
               {
                   if (a[i]> largest)
               }
            largest = a[i];

         // adds all the numbers together to find the sum
         for (i=0;i<n;i++)
           {
              sum=sum+a[i];
           }

        // calculates the average of the sum
        avg=sum/n;

        // display largest number
        cout << setw(45) << "Largest number is: " << largest << "\n" << endl;

        // displays the sum
        cout << setw(45) << "\nsum of array elements \n"<< sum;

        // displays the average
        cout << setw(45) << "\naverage of array elements \n"<< avg <<"\n";





//cout <<"0123456789 0123456789 0123456789 0123456789 0123456789 0123456789 0123456789 0123456789\n";

return 0;
}

}

1 个答案:

答案 0 :(得分:0)

尝试使用此代码查找数组中的最大数字

    #include <iostream>

    using namespace std;

int main()
{
    int n;
    cin>>n;
    int temp,a[n];
    for(int i=0;i<n;i++)
    {
        cin>>a[i];
    }
    temp=a[0];
    for(int i=1;i<n;i++)
    {
        if(a[i]>temp)
        {
            temp=a[i];
        }
    }
    cout << "Largest number is:" << temp <<endl;
    return 0;
}