Поэтому мне нужно ввести число в массив и найти и отобразить самый большой из чисел, я не уверен, что у меня будет лучший цикл для этого цикла. Кроме того, я не уверен, как настроить его, у меня есть большая часть кода, сделанного в меру моих возможностей.
#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;
}
}
попробуйте этот код, чтобы найти наибольшее число в массиве
#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;
}
temp = *std::max_element(a, a + n);