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lzIGl0cyBleHBlY3RlZCB2YWx1ZT8KPHA+SW5wdXQgY29uc2lzdHMgb2Ygc2V2ZXJhbCBTbWVlY2ggZXhwcmVzc2lvbnMsIG9uZSBwZXIgbGluZSwgZm9sbG93ZWQgYnkgYSBsaW5lIGNvbnRhaW5pbmcgKCkuIEZvciBlYWNoIGV4cHJlc3Npb24sIG91dHB1dCBpdHMgZXhwZWN0ZWQgdmFsdWUgdG8gdHdvIGRlY2ltYWwgcGxhY2VzLgo8L3A+CjxoMz5TYW1wbGUgSW5wdXQ8L2gzPgo8cHJlIGNsYXNzPQ=="brush:java;">7
(.5 3 9)
()
Output for Sample Input
7.00
3.00
題意:給出個表達式(p,e1,e2)表示(e1+e2)*p+(e1-e2)*(1-p)的結果,求最後的值
思路:遞歸的處理整個式子,注意細節小數的時候的判斷
#include
#include
#include
#include
using namespace std;
const int maxn = 10005;
char str[maxn];
int cur, len;
double cal() {
double op = 1;
while (!(str[cur]=='(' || (str[cur]>='0'&&str[cur]<='9') || str[cur]=='-') && cur < len)
cur++;
if (str[cur] == '-') {
cur++;
op = -1;
}
if (str[cur] == '(') {
cur++;
double w = 0.1, p = 0;
if (str[cur] == '.' || str[cur+1] == '.') {
if (str[cur+1] == '.')
cur++;
for (int i = cur+1; str[i] >= '0' && str[i] <= '9' && str[i]; i++, cur = i) {
p = p + (str[i] - '0') * w;
w *= 0.1;
}
}
else p = str[cur++] - '0';
double a, b;
a = cal();
b = cal();
return (a + b) * p + (a - b) * (1 - p);
}
else {
double p = 0;
for (int i = cur; str[i] >= '0' && str[i] <= '9' && str[i]; i++, cur = i)
p = p * 10 + str[i] - '0';
return op * p;
}
}
int main() {
double p, a, b;
while (gets(str) && strcmp(str, "()")) {
len = strlen(str);
cur = 0;
printf("%.2lf\n", cal());
}
return 0;
}