仅对数组中的偶数求和

时间:2014-03-20 19:47:57

标签: c arrays math sum division

在从用户输入十个数字作为输入之后,我想要将那些可被2整除的数字相加。

我可以从用户那里获得输入,但是我不知道如何检查哪些数字可以被2整除,并且只添加那些数字。

#include <stdio.h>
#include <ctype.h>

int main(void) {
    int i = 0; 
    int val;
    char ch;
    int numbers[10];

    while(i < 10) {

        val = scanf("%d%c", numbers + i, &ch);  

        if(val != 2 || !isspace(ch)) {
            while((ch = getchar()) != '\n')  // discard the invalid input
                ;  
            printf("Error! Entered number is not an integer.\n");
            printf("Please enter an integer again.\n");
            continue;
        }
        ++i;
    }
    printf("%d\n", numbers[0]);
    printf("%d\n", numbers[1]);
    printf("%d\n", numbers[2]);
    printf("%d\n", numbers[3]);
    printf("%d\n", numbers[4]);
    printf("%d\n", numbers[5]);
    printf("%d\n", numbers[6]);
    printf("%d\n", numbers[7]);
    printf("%d\n", numbers[8]);
    printf("%d\n", numbers[9]);

    return 0;
}

3 个答案:

答案 0 :(得分:4)

怎么样:

int sum = 0;
for (int i = 0; i <= 9; i++)
{
    if (numbers[i] % 2 == 0)
        sum += numbers[i];
}

答案 1 :(得分:0)

完全不必要的优化

int sum[2]={0};
for(size_t i = 0; i <=9; ++i) sum[numbers[i]&1]+=numbers[i];

答案 2 :(得分:0)

int main(void)
{
    int i;
    int numbers[10];
    int sum = 0;

    for(i=0; i<10; ++i)
    {
        printf("Enter #%d:\n", i+1);
        scanf("%d", numbers+i);

        if (numbers[i] % 2 == 0) // Then Number is even
        {
            sum += numbers[i];
        }
    }

    printf("The sum of only the even numbers is %d\n", sum);

    getch();
    return 0;
}