如何找到数组中的最大数并用c++显示

how to find the largest number in an array and display it in c++

本文关键字:c++ 显示 最大数 何找 数组      更新时间:2023-10-16

所以我需要将数字输入到一个数组中,并找到并显示最大的数字,我不确定我的循环是否是实现这一点的最佳方法。此外,我不确定如何设置它,我已经尽我所能完成了大部分代码,任何输入都将不胜感激!

#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 elementsn";
      // 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 0123456789n";
return 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;
}