我试图弄清楚为什么几乎相同的代码表现不同。
第一个运行良好(这里的scanf运算符放置在scanf操作数之前)
#include <stdio.h>
int main() {
char operator;
double first, second;
printf("Enter an operator (+, -, *,): ");
scanf("%c", &operator);
printf("Enter two operands: ");
scanf("%lf %lf", &first, &second);
switch (operator) {
case '+':
printf("%.1lf + %.1lf = %.1lf", first, second, first + second);
break;
case '-':
printf("%.1lf - %.1lf = %.1lf", first, second, first - second);
break;
case '*':
printf("%.1lf * %.1lf = %.1lf", first, second, first * second);
break;
case '/':
printf("%.1lf / %.1lf = %.1lf", first, second, first / second);
break;
// operator doesn't match any case constant
default:
printf("Error! operator is not correct");
}
return 0;
}
现在,第二个没有(这里的scanf操作数放在scanf运算符之前)
#include <stdio.h>
int main() {
char operator;
double first, second;
printf("Enter two operands: ");
scanf("%lf %lf", &first, &second);
printf("Enter an operator (+, -, *,): ");
scanf("%c", &operator);
switch (operator) {
case '+':
printf("%.1lf + %.1lf = %.1lf", first, second, first + second);
break;
case '-':
printf("%.1lf - %.1lf = %.1lf", first, second, first - second);
break;
case '*':
printf("%.1lf * %.1lf = %.1lf", first, second, first * second);
break;
case '/':
printf("%.1lf / %.1lf = %.1lf", first, second, first / second);
break;
// operator doesn't match any case constant
default:
printf("Error! operator is not correct");
}
return 0;
}
更改下面的代码,它将按您期望的方式工作。
当您输入两个数字时,您输入了: