UVA 11291

UVA 11291 - Smeech

题目链接

题意:给定一个表达式形如e=(p,e1,e2) 该表达式的值为 p(e1+e2)+(1p)(e1e2),求出值

思路:题目是非常水,可是处理起来还挺麻烦的,模拟写编译器LEX分析器原理去写了。

代码:

#include <cstdio>
#include <cstring>

const int N = 100005;
char str[N];
int now, len, token;
double value;

void gettoken() {
	while (str[now] == ' ') {now++;}
	if (str[now] == '(') {
		token = 0; now++;
	}
	else if (str[now] == ')') {
		token = 1; now++;
	}
	else if ((str[now] >= '0' && str[now] <= '9') || str[now] == '.' || str[now] == '-') {
		int flag = 1;
  		if (str[now] == '-') {
    		flag = -1;
    		now++;
  		}
  		value = 0;
		token = 2;
		while (now < len && str[now] >= '0' && str[now] <= '9') {
			value = value * 10 + str[now] - '0';
			now++;
		}
		if (str[now] == '.') {
			now++;
			double mu = 10;
			while (now < len && str[now] >= '0' && str[now] <= '9') {
				value += (str[now] - '0') / mu;
				mu *= 10;
    			now++;
   			}
  		}
  		value *= flag;
 	}
}

double expr() {
	gettoken();
	if (token == 0) {
		gettoken();
		double p = value;
		double x = expr();
		double y = expr();
		gettoken();
		return p * (x + y) + (1 - p) * (x - y);
 	}
 	else return value;
}

void init() {
	now = 0;
	len = strlen(str);;
}

int main() {
	while (gets(str) && strcmp(str, "()") != 0) {
		init();
		printf("%.2lf
", expr());
 	}	
	return 0;
}


原文地址:https://www.cnblogs.com/mqxnongmin/p/10874233.html