如何获得所有10个整数的偶数,奇数和总和的总和?

时间:2015-08-05 12:34:58

标签: c++

#include <iostream>

using namespace std;

int main()
{
    int num1=0, num2=0, num3=0, num4=0, num5=0, num6=0, num7=0, num8=0, num9=0, num10=0,even,odd,sum;

    cout<<"Enter (10) Integers :  ";
    cin>> num1>>num2>>num3>>num4>>num5>>num6>>num7>>num8>>num9>>num10;

    if(num1 %2==0)
      even=even + num1;
    else
      odd=odd+ num1;

    if(num2 %2==0)
      even=even + num2;
    else
      odd=odd+ num2;

    if(num3 %2==0)
      even=even + num3;
    else
      odd=odd+ num3;

    if(num4 %2==0)
      even=even + num4;
    else
      odd=odd+ num4;

    if(num5 %2==0)
      even=even + num5;
    else
      odd=odd+ num5;

    if(num6%2==0)
      even=even + num6;
    else
      odd=odd+ num6;

    if(num7 %2==0)
      even=even + num7;
    else
      odd=odd+ num7;

    if(num8%2==0)
      even=even + num8;
    else        
      odd=odd+ num8;

    if(num9 %2==0)
      even=even + num9;
    else
      odd=odd+ num9;

    if(num10 %2==0)
      even=even + num10;
    else
      odd=odd+ num10;

    sum = num1 + num2 + num3 + num4 + num5 + num6 + num7 + num8 + num9 + num10;

    cout<<"\nThe sum of ODD numbers is  "<<odd;


    cout<<" \nThe sum of EVEN numbers is "<<even;

    cout<<" \nThe sum of all input  numbers is "<<sum;

    return 0;

}

1 个答案:

答案 0 :(得分:0)

您应该使用此代码:

    int numarr[10];
    int sum = 0, even = 0, odd = 0;
    for (int i = 0; i < 10; i++)
    {
        cin >> numarr[i];
        if (numarr[i] % 2 == 0)
            even = even + numarr[i];
        else
            odd = odd + numarr[i];
        sum = sum + numarr[i];

    }

那些多个if-else陈述令人不悦。