【发布时间】:2017-01-22 05:36:43
【问题描述】:
我是 C 编程的初学者,我刚刚在我的代码中使用 if-else 语句制作了一个计算器。现在我尝试使用 switch 语句做同样的事情,但它总是执行默认值。请查看我的代码并建议我出了什么问题。 我目前正在 CodeBlock 中编写代码。
int main()
{
printf("\nWhat operation do you want to do:\n\tA)Addition\n\tB)Subtraction\n\tC)Multiplication\n\tD)Division\n");
float num1;
printf("Please enter the first number: ");
scanf("%f", &num1);
float num2;
printf("Please enter the second number: ");
scanf("%f", &num2);
char myChar;
scanf("%c", &myChar);
switch (myChar)
{
case 'A':
printf("The addition of %.2f and %.2f is %.2f", num1, num2, num1 + num2);
break;
case 'B':
printf("The subtraction of %.2f and %.2f is %.2f", num1, num2, num1 - num2);
break;
case 'C':
printf("The multiplication of %.2f and %.2f is %.2f", num1, num2, num1 * num2);
break;
case 'D':
printf("The quotient of %.2f and %.2f is %.2f", num1, num2, num1 / num2);
break;
default :
printf("You enterned incorrect input");
break;
}
return 0;
}
任何帮助将不胜感激
【问题讨论】:
-
char myChar; scanf("%c", &myChar);移动到float num1;之前 -
当您
scanf("%c", &myChar)时,您正在阅读第二个号码后留下的换行符。你的switch()没有这种情况,所以它运行默认值。 -
不要使用
scanf进行用户输入;使用fgets。 -
无法正确执行是一个绝对无用的错误描述,除非您解释无法正确执行是什么意思。您发布的代码有什么具体问题?
-
C scanf() issues?的可能重复