使用switch-statement在C中创建一个简单的计算器

时间:2017-01-22 05:36:44

标签: c scanf

我是C编程的初学者,我刚刚在我的代码中使用if-else语句完成了一个计算器。现在我尝试使用switch语句执行相同操作,但它始终执行默认值。请查看我的代码,并告诉我出了什么问题。 我目前正在CodeBlock中编写代码。

This is the message i'm getting

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;
}

任何帮助将不胜感激

1 个答案:

答案 0 :(得分:0)

您的问题主要与scanf有关,前一个输入的剩余\n被解释为该输入的输入。

此外,您的操作提示与其相应的输入不匹配。

建议修复:

float num1;
printf("Please enter the first number: ");
scanf("%f", &num1);

float num2;
printf("Please enter the second number: ");
scanf("%f", &num2);

printf("\nWhat operation do you want to do:\n\tA)Addition\n\tB)Subtraction\n\tC)Multiplication\n\tD)Division\n");
char myChar;
scanf(" %c", &myChar);

您可以添加printf作为调试目的 - 这也会有所帮助。第一个输入的示例:

float num1;
printf("Please enter the first number: ");
scanf(" %f", &num1);
printf("num1 = %f\n", num1 );