You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言程序求和异常:输入整数求和结果始终为0求助

Fixing Your C Program's Sum Calculation Issue

Hey there! Let's dig into why your sum is always stuck at 0—your code has a couple of straightforward fixes needed:

Key Problems in Your Current Code

  • You never add input values to sum during the loop: Right now, your sum = sum + x; line runs after you print the sum, and only once (after the loop exits). All the integers you entered before typing -1 never get added to sum, so it stays at its initial value of 0 when you print it.
  • Even if you moved the line, you'd accidentally add -1 to the sum: Since do-while runs the loop body first before checking the condition, when you type -1, it gets read into x before the loop exits. If you just moved the sum line into the loop without a check, that -1 would be included in your total, which isn't what you want.

Corrected Code

Here's the fixed version with explanations in comments:

#include <stdio.h>

int main() {
    int x; 
    int sum = 0; 
    printf("Please enter some integers man\n"); 
    do {
        scanf_s("%d", &x);
        // Only add the value to sum if it's not the exit signal (-1)
        if (x != -1) {
            sum += x; // Shorthand for sum = sum + x
        }
    } while (x != -1); 
    printf("\nSum is: %d\n", sum);
    return 0;
}

What Changed?

  1. Moved the sum logic into the loop: Now every time you enter a number, it's immediately considered for the total.
  2. Added an if check: This ensures we skip adding -1 to the sum, since that's your exit trigger, not a number to include.
  3. Cleaned up formatting: Breaking the code into lines makes it way easier to spot issues (your original one-liner was tough to debug at a glance!).
  4. Used sum += x as a shorthand: It's the same as sum = sum + x, just more concise—totally optional, but common in C code.

Now when you run this, it'll add up all your input integers, stop when you type -1, and print the correct total.

内容的提问来源于stack exchange,提问作者user9264468

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 10:05:05