对数组中的数字进行平方,找到总和和最大数字

Squaring numbers in array, finding the sum and the biggest number

本文关键字:数字 数组      更新时间:2023-10-16

我有一个任务是平方数组的所有元素,用","分隔它们,然后找到平方数组的总和并找到它的最大数字。我设法对它们进行平方并找到总和,但我找不到最大的数字,并且程序还在新数组的末尾打印","。 这是我的代码:

#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int a[10];
int n,sum=0,kiek=0,max=a[0];;
cin>>n;
for(int i=0;i<n;i++)
{cin>>a[i];
a[i]*=a[i];
sum=sum+a[i];
}
for (int i = 0 ; i < n ; i++) 
{   cout <<a[i] << ","; }
cout<<endl ;
cout<<"suma " <<sum;
cout<<endl;
for(int i=0;i<10;i++)
{if(max<a[i])
{
max = a[i];
} 
}
cout<<"max "<<max;
return 0;
}

这是我运行程序时结果的屏幕截图

#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int a[10];
int n, sum = 0;  // Remove some unused variables
// Input //
cin >> n;
for(int i = 0; i < n; i++){
cin >> a[i];
a[i] *= a[i];
sum += a[i];
}

// List a[] and sum //
for (int i = 0 ; i < n - 1 ; i++) {
cout << a[i] << ", ";
}
cout << a[n - 1] << endl; // Just for a little beauty
cout << "suma " << sum << endl;

// Find Max //
int max = a[0];  // max should be declared there, 
// because a[0] has not entered data at the first
for(int i = 0; i < n; i++) {  // use n, not 10
if(a[i] > max){
max = a[i];
} 
}
cout << "max " << max;

return 0;
}

猖獗。

请添加缩进,空格和注释,这是一个好习惯。

注释:如果要在运行时获取数组的大小,最好使用 STL 容器或指针。 您的问题就在这里:

---> for(int i=0;i<10;i++)
{if(max<a[i])

祝你好运。