C语言do while语句程序异常:输入天数被跳过且出现随机计算值
Hey there, let's break down the issues in your code one by one—they're all common beginner pitfalls, so no worries, we'll fix them up!
1. scanf 参数传递错误(核心问题导致输入跳过+随机值)
Your code has two critical mistakes with scanf:
- When reading a single character with
scanf, you need to use the%cformat specifier instead of%s(which is for strings). Also, you must pass the address of the variable using&—right now you're passingadirectly, which is invalid forscanf. Even worse, using%son a singlecharwill write beyond the variable's memory, causing undefined behavior. - For the integer input (
b), you're also not passing the address with&. This meansscanfis writing to a random memory location, which is why you're seeing random calculation values.
Fix for this part:
printf("Enter pet size (s/m/l): "); scanf(" %c", &a); // Note the space before %c to skip leftover newline characters printf("Enter number of days: "); scanf("%d", &b);
The space before %c is important—it tells scanf to ignore any whitespace (like the newline left in the input buffer after previous inputs) so it doesn't skip your input.
2. Assignment instead of comparison in conditionals
In your if/else if checks, you're using = (assignment operator) instead of == (comparison operator). This means you're setting a to 's'/'m' instead of checking if it equals those values. That's why your code might always take the first branch or behave unpredictably.
Fix example:
if (a == 's') { // Use == for comparison printf("Kennelling cost: %d\n", c); } else if (a == 'm') { printf("Kennelling cost: %d\n", d); } else { printf("Kennelling cost: %d\n", e); }
3. Do-while loop condition is always false
Your loop condition while (i = 0) is an assignment, not a check. This sets i to 0 every time, which evaluates to false—so the loop will only run once, not repeat as you probably intended. If you want the loop to run until the user chooses to stop, you could add a prompt to continue, or adjust the condition. For example, to keep looping until i is set to 1:
int i = 0; do { // ... your code ... printf("Do you want to calculate again? (0 for yes, 1 for no): "); scanf("%d", &i); } while (i == 0);
Full Fixed Code
Here's the complete corrected code with all fixes applied:
#include <stdio.h> int main() { char a; int b,c,d,e; int i = 0; do { printf("Enter pet size (s/m/l): "); scanf(" %c", &a); printf("Enter number of days: "); scanf("%d", &b); c = b * 8; d = b * 11; e = b * 14; if (a == 's') { printf("Kennelling cost: %d\n", c); } else if (a == 'm') { printf("Kennelling cost: %d\n", d); } else { printf("Kennelling cost: %d\n", e); } printf("Calculate another? (0=yes, 1=no): "); scanf("%d", &i); } while (i == 0); return 0; }
内容的提问来源于stack exchange,提问作者Rino

