UVA 11291 Smeech

【来源】https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=2266

此题比较简单,主要工作在于字符串的分割,怎么把代码写得漂亮点才是重点,可读性很重要。利用函数atof(stdlib.h)要比一位位去拼数字要方便点。

#include <iostream>
#include <stdio.h>
#include <cstring>
#include <stdlib.h>
#define MAXLEN 100005
using namespace std;

int SubExpLen(char* s, int start)
{
    int len=0;
    if(s[start]!='(')
    {
        while(s[start+len]!=' ')
        {
            len++;
        }
        return len;
    }

    //第一个字符是'('
    int num=1;
    len=1;
    while(num)
    {
        if(s[start+len]=='(')
            num++;
        if(s[start+len]==')')
            num--;
        len++;
    }
    return len;
}

double ToDouble(char* s, int start, int length)
{
    char sub[MAXLEN];
    strncpy(sub,s+start,length);
    sub[length]='\0';
    return atof(sub);
}

double Expression(char* s,int start,int length)
{
    int i=start;
    int len;
    double p,e1,e2;
    if(s[i]!='(')
        return ToDouble(s, start, length);

    i=i+1;
    len=SubExpLen(s, i);
    p=Expression(s, i, len);

    i=i+len+1;
    len=SubExpLen(s, i);
    e1=Expression(s, i, len);

    i=i+len+1;
    len=SubExpLen(s, i);
    e2=Expression(s, i, len);

    return p*(e1+e2)+(1-p)*(e1-e2);
}

int main()
{
    char s[MAXLEN];
    while(gets(s) && strcmp(s,"()")!=0)
    {
        printf("%.2lf\n",Expression(s,0,strlen(s)));
    }
    return 0;
}

 

你可能感兴趣的:(UVA 11291 Smeech)