[MOOC程序设计与算法二] 递归二
1.表达式计算 输入为四则运算表达式,仅由整数、+、-、* 、/ 、(、) 组成,没有空格,要求求其值。假设运算符结果都是整数 。"/"结果也是整数
表达式也是递归的定义:
表达式由项的+ -组成 ,项由因子的* / 组成, 因子可以是整数,也可以由带括号的表达式组成
判断是否还有表达式,项和因子,需要只读不取,根据读出的字符确定是否需要取,并做后面的运算,否则会出错。
cin.peek()只读一个字符而不取 cin.get()读取一个字符
代码:
#include <iostream> #include <stdio.h> #include <cstring> #include <algorithm> using namespace std; int factor_value() { int expression_value(void); int ret = 0; char c = cin.peek(); if (c == '(') { c = cin.get(); ret = expression_value(); cin.get(); } else { while (isdigit(c)) { c = cin.get(); ret = ret*10 + c -'0'; c = cin.peek(); } } return ret; } int term_value() { int ret = factor_value(); char c = cin.peek(); while (1) { if (c == '*' || c == '/') { c = cin.get(); if (c == '*') ret *= factor_value(); else ret /= factor_value(); c = cin.peek(); } else break; } return ret; } int expression_value() { int ret = term_value(); char c = cin.peek(); while (1) { if (c == '+' || c == '-') { c = cin.get(); if (c == '+') ret += term_value(); else ret -= term_value(); c = cin.peek(); } else break; } return ret; } int main() { freopen("1.txt", "r", stdin); cout << expression_value() << endl; return 0; }