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
sumduring the loop: Right now, yoursum = sum + x;line runs after you print the sum, and only once (after the loop exits). All the integers you entered before typing-1never get added tosum, so it stays at its initial value of 0 when you print it. - Even if you moved the line, you'd accidentally add
-1to the sum: Sincedo-whileruns the loop body first before checking the condition, when you type-1, it gets read intoxbefore the loop exits. If you just moved the sum line into the loop without a check, that-1would 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?
- Moved the sum logic into the loop: Now every time you enter a number, it's immediately considered for the total.
- Added an
ifcheck: This ensures we skip adding-1to the sum, since that's your exit trigger, not a number to include. - 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!).
- Used
sum += xas a shorthand: It's the same assum = 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
相关产品推荐
相关产品推荐

