如何在数组中找到最大数,并用C++显示
所以我需要将数字输入一个数组,找到并显示最大的数字,我不确定我的循环是否是最好的方法。此外,我对如何设置它不是积极的,我已经尽我所能完成了大部分代码,任何输入都将不胜感激如何在数组中找到最大数,并用C++显示,c++,arrays,C++,Arrays,所以我需要将数字输入一个数组,找到并显示最大的数字,我不确定我的循环是否是最好的方法。此外,我对如何设置它不是积极的,我已经尽我所能完成了大部分代码,任何输入都将不胜感激 #include <iostream> #include <iomanip> #include <cstdlib> using namespace std; int main() { // initialize the CONSTANTS const int SENTINEL = -1
#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;
}
你甚至不需要数组。如果你想查看代码而不是实际答案,你应该在codereview.stackexchange.com上发布。你会在那里得到更快的反馈。我知道我不需要阵列,我没有阵列就完成了,但是教练要求放一个阵列。。。Paul Thank ThoughThank Nischaal我也会查看该网站!我想有一次你想写一些东西,比如如果a[I]>max=a[I];但是你最后把if放在了一个循环中,最大的=在循环结束后。这甚至可以编译吗?但如果你把最大的=往上移动一行,它看起来可能会起作用。糟糕的编码风格导致了这一错误;还有一个很好的理由尝试代码审查网站。我拿出了第一部分,只是使用了temp=a[0]中的代码;下来,它就像一个魅力,非常感谢!温度=*标准::最大元素a,a+n;