题目链接:https://cn.vjudge.net/problem/OpenJ_Bailian-4132
题目描述:
求一个可以带括号的小学算术四则运算表达式的值
Input:
一行,一个四则运算表达式。'*'表示乘法,'/'表示除法
Output:
一行,该表达式的值,保留小数点后面两位
Sample Input:
输入样例1: 3.4 输入样例2: 7+8.3 输入样例3: 3+4.5*(7+2)*(3)*((3+4)*(2+3.5)/(4+5))-34*(7-(2+3))
Sample Output:
输出样例1: 3.40 输出样例2: 15.30 输出样例3: 454.75
题目解析:
表达式运算符优先级:① () ② * / ③ + -
而括号里又有可能包括一个含有多个运算符的表达式。
不懂cin.peek()和cin.get()看这里:https://blog.csdn.net/fenoix/article/details/77100216
代码:
#include <iostream>
#include <cmath>
#include <cstdio>
using namespace std;
double expression_value();
double factor_value() // 看是否有括号
{
bool flag = 0;
double next = 10;
double result = 0;
char op = cin.peek();
if( op == '(') {
cin.get();
result = expression_value(); // 括号里可能是一个含多个运算符的表达式,需要从基层开始读
cin.get();
}
else {
while( (op <= '9' && op >= '0') || op == '.') {
if(op == '.') {
next = 1;
flag = 1;
cin.get();
op = cin.peek();
}
if(flag) {
next *= 0.1;
result += next*(op - '0');
cin.get();
op = cin.peek();
}
else {
result = next*result + op - '0';
cin.get();
op = cin.peek();
}
}
}
return result;
}
double term_value() // 看是否有乘除
{
double result = factor_value(); // 看是否有括号
while( true) {
char op = cin.peek();
if( op == '*' || op == '/') {
cin.get();
double value = factor_value();
if( op == '*')
result *= value;
else
result /= value;
}
else
break;
}
return result;
}
double expression_value()
{
double result = term_value(); // 看是否有乘除
while( true) {
char op = cin.peek();
if( op == '+' || op == '-') {
cin.get();
double value = term_value();
if( op == '+')
result += value;
else
result -= value;
}
else
break;
}
return result;
}
int main()
{
printf("%.2lf",expression_value());
return 0;
}