我被分配了一项学校任务。 在此任务中,我必须用 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/