我試圖用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