簡體   English   中英

對數組中的數字進行平方,找到總和和最大的數字

[英]Squaring numbers in array, finding the sum and the biggest number

我的任務是將數組的所有元素平方,用“,”分隔它們,然后找到平方數組的總和並找到它的最大數。 我設法將它們平方並找到總和,但我找不到最大的數字,並且程序還在新數組的末尾打印“,”。 這是我的代碼:

#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])

祝你好運。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM