求助:无法定位C语言Switch语句程序中的错误
Hey there! I see you're just starting out with software engineering and ran into some bugs in your calculator program—let's break down what's going wrong and fix them together.
1. The Hidden Newline Character Problem
The biggest issue is with how you're reading the operation character. When you use scanf("%d") to input a and b, after entering each number you press Enter, which leaves a newline character (\n) in the input buffer. The next scanf("%c") reads this newline instead of the actual operation you type, so your switch statement never hits the cases you expect.
Fix: Add a space before %c in the scanf call to skip any whitespace (including newlines):
scanf(" %c", &operation);
2. Non-Standard main Function Return Type
In standard C, the main function should return an int instead of void. This is a best practice and ensures your program exits correctly.
Fix: Change void main() to int main() and add return 0; at the end of the function.
3. Uninitialized Variable e
If the user enters an invalid operation (like %), the default case runs but doesn't assign a value to e. When you print e later, it will hold a random garbage value—this is undefined behavior.
Fix: Initialize e when declaring it, or handle the invalid case properly to avoid printing an uninitialized value:
int a, b, e = 0;
4. Division by Zero Risk
Right now, if the user enters 0 as the second number and selects division, your program will crash with a division-by-zero error. We need to add a check for this.
Fix: Add a condition inside the / case to verify b isn't zero:
case '/' : if (b == 0) { printf("Error: Cannot divide by zero!\n"); return 1; // Exit with error code } e = a / b; break;
Full Fixed Code
Here's the complete corrected program incorporating all these fixes:
#include <stdio.h> int main() { int a, b, e = 0; char operation; printf("enter the first number: "); scanf("%d", &a); printf("enter the second number: "); scanf("%d", &b); printf("enter the operation: "); scanf(" %c", &operation); switch (operation) { case '+' : e = a + b; break; case '-' : e = a - b; break; case '*' : e = a * b; break; case '/' : if (b == 0) { printf("Error: Cannot divide by zero!\n"); return 1; } e = a / b; break; default: printf("wrong choice!!\n"); return 1; // Exit early to avoid printing uninitialized e } printf("%d %c %d = %d \n", a, operation, b, e); return 0; }
Give this a try—it should work as expected now. Let me know if you have any other questions as you keep learning C!
内容的提问来源于stack exchange,提问作者Jaouadi

