我试图用c中的+, - ,*和/运算符来制作简单的计算器。例如((2.1 - 5.6)*4)+(2.8+2/2.2)
应该是-10.29 ...我尝试过这样,但它只适用于出门bar。如果用户的输入包含括号,我不知道如何处理。用括号括起来的c中的简单计算器
float calc(void)
{
float x,y, parse;
char c;
int test = scanf("%f %c %f", &x,&c,&y);
if (test == 0){ // if '(' starts equation
parse = calc();
}
else{
if (c == '-'){
return x - y;
}
else if (c == '/'){
return x/y;
}
else if (c == '+'){
return x + y;
}
else if (c == '*'){
return x * y;
}
}
}
你要打破这种分为两个问题:1)找到所有的支架,配对起来,找到自己最里面的内容; 2)评估这些内容。它成为一个递归代码 - 详细解释这个范围的范围超出了StackOverflow的范围。 – Floris
你可能想看看这个:http://en.wikipedia.org/wiki/Shunting-yard_algorithm –
甚至http://stackoverflow.com/questions/4582398/writing-a-simple-equation-parser – Floris