繁体   English   中英

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

[英]c programming - Why this simple calculator using switch doesn't work

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

第一个运行良好(这里 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;
   }

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

3.141 2.71828\n

注意末尾的换行符。 换行符不是 double ( %lf ) 的一部分,因此它没有从输入缓冲区中读取到second 相反,换行符( \\n )留在输入缓冲区中。

下一个scanf用于字符( %c )。 它得到了哪个角色? 它得到了换行符!

所以你的变量operand有字符\\n

要修复它,请制作您的 scanfs:

scanf("%lf %lf ", &first, &second);
scanf("%c ", &operator);   // Note the extra space at the end of each format-string

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM