计算表达式的c程序

标签 c

我编写了这个程序来计算像“2 + 6 - 9”这样的表达式(数字和运算符之间有空格),但最后一个 if block 不正确。如何在收到\n 时中断循环,如果没有则存储输入。

#include <stdio.h>
#include<stdlib.h>

void main()
{
    char oper;
    int sum,y;
    scanf("%d %c",&sum,&oper);
    while(1)
    {
                scanf("%d",&y);

                if(oper=='+')
                        sum += y;
                else if(oper=='-')
                        sum -= y;
                else if(oper=='/')
                        sum /= y;
                else if(oper=='*')
                        sum += y;
                if((scanf("%c",&oper))=='\n')
                        break;
        }
        printf("\n =%d",sum);
}

最佳答案

参见the documentation for scanf

On success, the function returns the number of items of the argument list successfully filled.

替换这部分:

if((scanf("%c",&oper))=='\n')
    break;

与:

if(scanf("%c",&oper) && oper=='\n')
    break;

这个:

  • 检查scanf()是否已将任何值放入oper
  • 如果是,则检查该值是否等于\n

关于计算表达式的c程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47969074/

相关文章:

c - 二叉树中插入错误或指针错误

c - 这一段C代码会按我的意愿去做吗?

c - 使用数组来统计选票

c - 如何使用 'key' : C 进行排序

c - while 循环在 c 中未按预期工作

c - c语言不分配内存空间访问有问题吗

x86 中内存分段的困惑

c - 如果在IOCP模型中指定了WSASend的lpCompletionRoutine怎么办?

c - 将 char** 数组的特定元素设置为 NULL

使用字符指针计算数组索引