一个简单的“打印”计算器

时间:2016-12-04 17:35:16

标签: c calculator

当我输入数字时,我看到了 输入数字1 输入运算符ERROR:未知运算符! 累加器= 0.000000 输入数字

为什么步骤 - printf("键入运算符")被跳过并替换为 - default:             printf("错误:未知运算符!\ n");             打破;

提前感谢您的帮助!

// Program to produce a simple printing calculator

#include <stdio.h>
#include <stdbool.h>

int main (void)
{

    double accumulator = 0.0, number; // The accumulator shall be 0 at startup
    char operator;
    bool isCalculating = true;  // Set flag indicating that calculations are ongoing


    printf("You can use 4 operator for arithmetic + - / *\n");
    printf("To set accumulator to some number use operator S or s\n");
    printf("To exit from this program use operator E or e\n");
    printf ("Begin Calculations\n");

    while (isCalculating)   // The loop ends when operator is = 'E'
    {

        printf("Type in a digit ");
        scanf ("%lf", &number);             // Get input from the user.

        printf("Type in an operator ");
        scanf ("%c", &operator);
        // The conditions and their associated calculations
        switch (operator)
        {
        case '+':
            accumulator += number;
            break;
        case '-':
            accumulator -= number;
            break;
        case '*':
            accumulator *= number;
            break;
        case '/':
            if (number == 0)
                printf ("ERROR: Division by 0 is not allowed!");
            else
                accumulator /= number;
            break;
        case 'S':
        case 's':
            accumulator = number;
            break;
        case 'E':
        case 'e':
            isCalculating = false;
            break;
        default:
            printf ("ERROR: Unknown operator!\n");
            break;
        }

        printf ("accumulator = %f\n", accumulator);
    }
    printf ("End of Calculations");

    return 0;
}

1 个答案:

答案 0 :(得分:2)

对于char,

scanf会使用换行符。因此扫描的字符是“换行”而不是您期望的字符。

我换了:

scanf ("%c", &operator);

通过

scanf ("%*c%c", &operator);

(在运营商之前消费换行而不使用%*c格式分配)

你的代码工作正常。