Sam*_*sel 1 c calculator break switch-statement
我正在尝试编写一个简单的计算器.
这是我的代码:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
char operator = 0;
float num1 = 0.0;
float num2 = 0.0;
float sol = 0.0;
while (operator != 'q') {
printf("Operator: ");
scanf("%c", &operator);
printf("First Number: ");
scanf("%f", &num1);
printf("Second Number: ");
scanf("%f", &num2);
switch (operator)
{
case '+': sol = num1 + num2; break;
case '-': sol = num1 - num2; break;
case '*': sol = num1 * num2; break;
case '/': sol = num1 / num2; break;
case 'q': printf("Finished!"); exit(0);
default: printf("Error!"); exit(0);
}
printf("The solution is: %.2f\n\n", sol);
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
所以对我来说代码很好.正如您所看到的,我使用while循环执行此操作,您可以计算直到键入'q'作为运算符.循环的第一次运行工作正常,但它变得令人毛骨悚然(我的控制台):
Operator: +
First Number: 5
Second Number: 4
The solution is: 9.00
Operator: First Number:
Run Code Online (Sandbox Code Playgroud)
为什么程序不允许我在第二次循环运行中输入运算符?
大多数带有scanf的格式说明符都会跳过前导空格.%c才不是.
scanf("%f", &num2);在第一次迭代结束时,在输入缓冲区中留下一个换行符.
scanf("%c", &operator);在第二次迭代开始时,读取换行符并继续.
使用空间之前%c在scanf(" %c", &operator);将允许%c跳过前导空格和捕捉操作.