c - 奇数相加不正确

标签 c for-loop

做一个练习,从用户那里获取 5 个整数,然后仅将奇数相加。所有内容加起来都是正确的,直到最后一个数字由于某种原因弄乱了所有内容:

Code and Test

#include <stdio.h>

int main() {
    int userNum[5];
    int i;
    int sum = 0;

    for (i = 1; i <= 5; ++i) {
        printf("Please enter number %d:\n", i);
        scanf("%d", &userNum[i]);

        if (userNum[i] % 2 > 0) {
            sum = sum + userNum[i];
        }
    }
    printf("The sum of all odd integers is: %d", sum);

    return 0;
}

最佳答案

您正在将 5 个数字读入数组元素 userNum[1]userNum[5],但由于在 C 中数组索引从 0 开始, userNum[5] 不存在,并且当程序尝试存储超出数组末尾的数字时,程序会出现未定义的行为。其他一些变量被修改并且输出是假的。未定义的行为实际上可能会产生更糟糕的后果,例如假候选人以比对手少的票数赢得选举:)

这是更正后的版本:

#include <stdio.h>

int main() {
    int userNum[5];
    int i;
    int sum = 0;

    for (i = 0; i < 5; ++i) {
        printf("Please enter number %d:\n", i + 1);
        if (scanf("%d", &userNum[i]) != 1) {
            printf("invalid input\n");
            return 1;
        }
        if (userNum[i] % 2 > 0) {
            sum = sum + userNum[i];
        }
    }
    printf("The sum of all odd integers is: %d\n", sum);

    return 0;
}

关于c - 奇数相加不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58806378/

相关文章:

C - 读取 scanf 直到 feof(stdin),不输出错误

c - OpenCL:从 'int *' 到 '__generic int *__generic *' 的转换

c - dsPIC33EP512MU810 ADC channel 到引脚的映射

c - 这个 for 循环的条件是做什么的?

c - 如何从 fgets 中获取正在读取的行的长度并对其进行循环

linux - 如何在 bash 脚本中递归地执行 foreach *.mp3 文件?

c - 在 C 中使用模板函数的最短示例?

c - 打印时错误地将宏转换为 int

python - 循环删除缺失值数量的列

javascript - 如何从多维数组中迭代表中的数据