(再帰的)は、4件の演算式の評価 - 学習アルゴリズム

問題

四つの演算式を入力すると、整数のみ、+である、 - 、
*、/、(、)
必要な値を求めないスペースを有します。仮定の結果は整数演算子です
「/」結果も整数であります
ここに画像を挿入説明
ここに画像を挿入説明

コード:
//郭威北京大学からの
サンプル


输入:(2+3)*(5+7)+9/3
输出: 63

#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
int factor_value();
int term_value();
int expression_value();
int main()
{
cout << expression_value() << endl;
return 0;
}

int expression_value() //求一个表达式的值
{
int result = term_value(); //求第一项的值
bool more = true;
while( more) {
char op = cin.peek(); //看一个字符,不取走
if( op == '+' || op == '-' ) {
cin.get(); //从输入中取走一个字符
int value = term_value();
if( op == '+' ) result += value;
else result -= value;
}
else more = false;
}
return result;
}

int term_value() //求一个项的值
{
int result = factor_value(); //求第一个因子的值
while(true) {
char op = cin.peek();
if( op == '*' || op == '/') {
cin.get();
int value = factor_value();
if( op == '*') 
result *= value;
else result /= value;
}
else 
break;
}
return result;
}

int factor_value() //求一个因子的值
{
int result = 0;
char c = cin.peek();
if( c == '(') {
cin.get();
result = expression_value();
cin.get();
}
else {
while(isdigit(c)) {
result = 10 * result + c - '0';
cin.get();
c = cin.peek();
} }
return result;
}
公開された79元の記事 ウォンの賞賛133 ・は 40000 +を見て

おすすめ

転載: blog.csdn.net/weixin_45822638/article/details/105028789