2013
12-23

Smeech

Professor Octastichs has invented a new programming language, Smeech. An expression in Smeech may be a positive or negative integer, or may be of the form (p e1 e2) where p is a real number between 0 and 1 (inclusive) and e1 and e2 are Smeech expressions. The value represented by a Smeech expression is as follows:
1) An integer represents itself
2) With probability p, (p e1 e2) represents x+y where x is the value of e1 and y is the value of e2; otherwise it represents x-y.
Given a Smeech expression, what is its expected value?

Input consists of several Smeech expressions, one per line, followed by a line containing ().

For each expression, output its expected value to two decimal places.

7
(.5 3 9)
()

7.00
3.00

#include<stdio.h>
#include<string.h>
#include<math.h>
char s[1248];
{
double ans,p,x,y;
int i,j,n;
if(s[0]!='(')//输入的就是一个数字
{
sscanf(s,"%lf",&ans);//字符串转换为double
return ans;
}
sscanf(s+1,"%lf",&p);
i=0;
while(s[i++]!=' ');       //while(s[i]!=' ')    {  i++;   }
if(s[i]!='(')
{
sscanf(s+i,"%lf",&x);
while(s[i++]!=' ');
if(s[i]!='(')   sscanf(s+i,"%lf",&y);
}
else
{
n=1;
for(j=i+1;n;j++)//左右括号的析取抵消
{
if(s[j]=='(')   ++n;
if(s[j]==')')     --n;
}
s[j]='\0';
else              sscanf(s+j+1,"%lf",&y);
}
return x+(p+p-1)*y;
}
int main()
{
while(gets(s))
{
if(strcmp(s,"()")==0)     break;
}