c编程-为什么这个使用开关的简单计算器不起作用

问题描述 投票:-1回答:2

我试图弄清楚为什么几乎相同的代码表现不同。

第一个运行良好(这里的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;
   }
c switch-statement
2个回答
0
投票

更改下面的代码,它将按您期望的方式工作。


-1
投票

当您输入两个数字时,您输入了:

© www.soinside.com 2019 - 2024. All rights reserved.