使用 getchar() 在 C 中计算数学表达式

标签 c

我被分配了一项学校任务。 在此任务中,我必须用 C 语言创建一个程序,该程序读取用户输入的数学表达式并返回其结果。例如,输入必须是 30 + 400,在这种情况下,输出必须是 30 和 400 相加的结果,即 430。除了加法和其他数学运算(减法、乘法、除法)。每个表达式都必须在一行中读取,而且我不允许在我的代码中使用数组或任何其他复杂的数据结构。 我已经尝试了一些方法来解决这个任务,但我不明白如何将数字与运算符分开以便计算表达式。 这是我写的:

#include <stdio.h>

int main(){
    int ch,result;
    int plus;
    int minus;
    int mult; 
    int div;
    while((ch = getchar())!= EOF){
        plus = 0;
        minus = 0;
        mult = 0;
        div = 0;
        if (ch != '\n'){
            if (ch >= '0' && ch <='9'){ //Checks if the character is a number
                result += ch;
            }else if(ch== '+'){//Checks if the character is an operator
                plus =1;
            }else if(ch== '-'){
                minus = 1;
            }else if(ch == '*'){
                mult = 1;
            }else if(ch== '/'){
                div = 1;
            }

        }
        printf("%d\n",result); 
    }

}

任何建议或想法都会很有帮助。 附言我为我的英语感到抱歉,如果我不能使用适当的术语来描述这个问题。

最佳答案

getchar 返回您需要将其转换为十进制的 ASCII 值。

您可以使用两个整数来存储输入的数字并对其进行操作。

示例:

int num1 = 0,num2 = 0;
char op;
int state = 0;
while((ch = getchar())!= EOF){

    if (ch != '\n'){
        if (ch >= '0' && ch <='9'){ //Checks if the character is a number
           if (state == 0) 
           num1 = num1*10 + ch- '0'; // Convert ASCII to decimal
           else 
           num2 = num2*10 + ch- '0'; // Convert ASCII to decimal
        }else {
        /* Operator detected now start reading in second number*/
        op = ch;
        state = 1;
       }
    }
    else {
       int result =0;
       switch(op)
       {
         case '+':
            result = num1 + num2;
         break;
         case '-':
            result = num1 - num2;
         break;
         case '*':
            result = num1 * num2;
         break;
         case '/':
            result = num1 / num2;
         break;
       }
      printf("%d\n",result); 
      num1 = 0;
      num2 = 0;
      state = 0;
   }

关于使用 getchar() 在 C 中计算数学表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53575314/

相关文章:

计算字符串或文件中的字符数

c - 使用 opencv 构建自定义 ffmpeg4.1 时出错

c - yacc 缺少左括号的错误处理

c++ - 释放包含 malloc 字符串的 malloc 结构

使用 mknod() 创建目录

c - "field"参数从何而来?

c - 在 while 循环中从 c 中的文件读取

objective-c - 为什么 Xcode 编译器不会针对指针类型安全自动出错?

c - 带有 scanf 的程序在 NetBeans 中无法正常工作

c - 基于星/点的图像配准