c语言的计算器(累加器)

Calculator(accumulator) in c programming language

我想用 c 编写基本计算器: 我遇到累加器问题(使用“+”和“-”运算符)

int main(void)
{
    float num1,num2,res;
    char operator;

    printf ("Type in your expression.\n");
    scanf ("%f %c %f", &num1, &operator, &num2);

    if(operator == 'S'){
        printf(" = %.2f\n",num1);
        res = num1;
        while(1){
            printf ("Type in your expression.\n");
            scanf ("%c %f", &operator, &num2);
            if(operator == '+'){
                res += num2;
                printf("%.2f\n", res);
            }
            else if(operator == '-'){
                res -=num2;
                printf("%.2f\n",res);
            }
            else if(operator == '*'){
                res *=num2;
                printf("%.2f\n",res);
            }
            else if(operator == '/'){
                if(num2 == 0)
                    printf("Division by zero\n");
                else
                    res /=num2;
                    printf("%.2f\n",res);

            }
            else if(operator == 'E'){
                printf("End of the calculation:");
                printf("%.2f",res);
                break;

            }
        }     
    } 

在这部分代码中,除法和乘法工作正常: 但是当我在累加器中输入类似“+3”或“-2”的东西时,什么也没有发生。我不知道问题出在哪里。

我认为这是因为在下面的命令中:

scanf ("%c %f", &operator, &num2);

当您在程序等待读取运算符和数字时键入 +3 时,它将 +3 作为数字而不是 + 作为运算符和 3 作为数字。所以您必须给出 + 3(与作为快速分离)。我试过了,我认为它有效!!

%c 不会自动跳过 whitespace。将扫描格式字符串更改为:

        scanf (" %c%f", &operator, &num2);

这会将第一个非白色 space 字符插入 operator