【问题标题】:Calculator(accumulator) in c programming languagec语言中的计算器(累加器)
【发布时间】:2017-01-12 22:06:26
【问题描述】:

我想用 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”这样的小费时,什么也没有发生。我不知道问题出在哪里。

【问题讨论】:

标签: c if-statement calculator


【解决方案1】:

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

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

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

【讨论】:

  • 感谢您的回答!
【解决方案2】:

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

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

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

【讨论】:

  • 感谢您的回答!
猜你喜欢
  • 2012-05-14
  • 1970-01-01
  • 2013-12-03
  • 1970-01-01
  • 1970-01-01
  • 2020-02-18
  • 1970-01-01
  • 1970-01-01
  • 2022-10-06
相关资源
最近更新 更多