首页 > 解决方案 > 使用 getchar() 在 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); 
    }

}

任何建议或想法都会非常有帮助。PS我很抱歉我的英语,如果我用适当的术语来描述这个问题。

标签: c

解决方案


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

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

例子:

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;
   }

推荐阅读