标签:
题目链接:http://poj.org/problem?id=1686
思路分析:该问题为表达式求值问题,对于字母使用浮点数替换即可,因为输入中的数字只能是单个digit。
代码如下:
#include <iostream> #include <cstring> #include <cstdio> #include <cmath> #include <cstdlib> #include <string> using namespace std; const int MAX_N = 100; const double factor = 1.1; double number[MAX_N]; char str[MAX_N]; int len, pos; double Expression( ); double Term( ); double Factor( ); void InputExpression( ) { int i = 0; pos = 0; string str_in; getline(cin, str_in); for (i = 0, len = 0; i < str_in.length( ); ++i, ++len) str[len] = str_in[i]; str[len] = ‘\0‘; } char GetCurrentToken( ) { while (str[pos] == ‘ ‘ || str[pos] == ‘\t‘) pos++; return str[pos]; } char GetNextToken( ) { ++pos; while (str[pos] == ‘ ‘ || str[pos] == ‘\t‘) pos++; if (pos == len) return ‘\n‘; else return str[pos]; } double Expression( ) { char ch; double term1 = Term( ); while ((ch = GetCurrentToken( )) == ‘+‘ || (ch == ‘-‘)) { GetNextToken( ); double term2 = Term( ); if (ch == ‘+‘) term1 += term2; else term1 -= term2; } return term1; } double Term( ) { char ch; double factor_1 = Factor( ); while ((ch = GetCurrentToken( )) == ‘*‘) { GetNextToken( ); double factor_2 = Factor( ); factor_1 *= factor_2; } return factor_1; } double Factor( ) { double value = 0.0; char ch = GetCurrentToken( ); if (ch == ‘(‘) { GetNextToken( ); value = Expression( ); GetNextToken( ); } else if (isdigit(ch)) { value = ch - ‘0‘; GetNextToken( ); } else if (ch == ‘\n‘) value = -1; else { if (number[ch - ‘A‘] == 0) value = number[ch - ‘A‘] = (ch - ‘A‘) * 1.1; else value = number[ch - ‘A‘]; GetNextToken( ); } return value; } int main( ) { int case_time; scanf("%d\n", &case_time); while (case_time--) { InputExpression( ); double ans_1 = Expression( ); InputExpression( ); double ans_2 = Expression( ); if (abs(ans_1 - ans_2) < 1e-6) printf("YES\n"); else printf("NO\n"); } return 0; }
poj 1684 Lazy Math Instructor(字符串)
标签:
原文地址:http://www.cnblogs.com/tallisHe/p/4970472.html