正常表达式求值
?
編寫一個(gè)程序求正常表達(dá)式的值
例:5+6*9 (中間沒有空格)
下面是表達(dá)式的定義
顯然這是一個(gè)間接的遞歸
1 #include <iostream> 2 #include <cstdio> 3 #include <cstdlib> 4 using namespace std; 5 6 int expression_value(); 7 int term_value(); 8 int factor_value(); 9 10 int main() 11 { 12 printf("%d\n",expression_value()); 13 return 0; 14 } 15 int expression_value()//表達(dá)式 16 { 17 int more = 1; 18 int result = term_value();//第一項(xiàng)的值 19 char op; 20 while(more){//如果是不斷用 + - 連接 則不斷進(jìn)行循環(huán) 21 op = cin.peek();//從流輸入中復(fù)制到OP中 不是 取走 22 if(op == '+' || op == '-') 23 { 24 cin.get(); 25 if(op == '+') 26 result+=term_value();//如果是 + - 就 + - 下一項(xiàng)的值 27 else 28 result-=term_value(); 29 } 30 else more = 0; // 如果不是+ - 則停止循環(huán) 31 } 32 return result; 33 } 34 int term_value() 35 { 36 int more = 1; 37 int result = factor_value(); 38 char op; 39 while(more){ 40 op = cin.peek(); 41 if(op == '*' || op == '/') 42 { 43 cin.get(); 44 if(op == '*') 45 result *= factor_value(); 46 else 47 result /= factor_value(); 48 } 49 else more = 0; 50 } 51 return result; 52 } 53 54 int factor_value() 55 { 56 int result = 0; 57 int op; 58 op = cin.peek(); 59 if(op == '('){ 60 cin.get(); 61 result += expression_value(); 62 cin.get(); 63 } 64 else 65 while(isdigit(op)) //檢驗(yàn)字符是否是阿拉伯?dāng)?shù)字 66 { 67 result = result * 10 + op - '0'; // 每多輸入一位 相當(dāng)于 之前輸入的數(shù)字大十倍 并且加上 剛才輸入的數(shù) 68 cin.get(); 69 op = cin.peek(); 70 } 71 return result; 72 }cin.peek() 從流輸入中復(fù)制到一個(gè)對(duì)象中 并不是取走 此時(shí)流輸入沒有變化
cin.get() 從流輸入中取走一個(gè)字符
isdigit() 檢驗(yàn)char型對(duì)象中的值是否為阿拉伯?dāng)?shù)字 若是'5'則返回1 'P'則返回0
?
轉(zhuǎn)載于:https://www.cnblogs.com/16-CHQ/p/6663847.html
總結(jié)
- 上一篇: iOS原生布局简介
- 下一篇: Excel信息提取之二