uva 327 Evaluating Simple C Expressions

题意 : 给定一个表达式求值,还有求值结束后变量的值

解题思路:字符串预处理

解题代码:

// File Name: uva372.c
// Author: darkdream
// Created Time: 2013年05月21日 星期二 20时57分27秒

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<time.h>
#include<math.h>
#include<ctype.h>
char str[10000];
int main(){

   //freopen("/home/plac/problem/input.txt","r",stdin);
   //freopen("/home/plac/problem/output.txt","w",stdout);
   while(gets(str))
   {
      bool a[30] = {0};
      int num[30];
      int add[30] = {0};
      char temp[10000] = {0};
      memcpy(temp,str,10000);
      for(int i = 1;i <= 28;i ++)
      {
         num[i] = i ;
      }
     int sum = 0, j = -1 ;
     for(int i = 0 ;i < strlen(str); i ++)
     {
           if(str[i] != ' ')
           {
            j++;
            str[j] = str[i];
           }
     }
     str[j+1] = '\0' ;
      for(int i = 0;i < strlen(str); i++)
      {
         if(isalpha(str[i]))
         {
            int k = str[i] - 'a' +1;
             a[k] = 1;
            if(i > 1)
            {
              if(str[i-1] == '+' && str[i-2] == '+')
              {
                  num[k]++; 
                  str[i-1] = str[i-2] = ' ';
              }
              else if(str[i-1] == '-' && str[i-2] == '-')
              {
                  num[k]--;
                  str[i-1] = str[i-2] = ' ';
              }

            }
            if(strlen(str) - i >= 3)
            {
              if(str[i+1] == '+' && str[i+2] == '+')
              {
                  add[k]++;
                  str[i+1] = str[i+2] = ' ';
              }
              else if(str[i+1] == '-' && str[i+2] == '-')
              {
                  add[k]--;
                  str[i+1] = str[i+2] = ' ';
              }
            
            }
         }

      }
      memset(temp1,0,sizeof(temp1));
      j = -1 ;
     for(int i = 0 ;i < strlen(str); i ++)
     {
           if(str[i] != ' ')
           {
            j++;
            str[j] = str[i];
           }
     }
     str[j+1]  = '\0';
     sum = num[str[0]-'a'+1];
     for(int i = 1;i < strlen(str) ;i ++)
     {
        if(isalpha(str[i]))
        {
          if(str[i-1] == '-' )
              sum -= num[str[i]-'a'+1];
          else
              sum += num[str[i]-'a'+1];
        }
     }
     for(int i = 1; i< 28;i ++)
     {
        num[i] = num[i]+ add[i];
     }
     printf("Expression: %s\n",temp);
     printf("    value = %d\n",sum);

     for(int i =1 ;i < 28; i ++)
     {
        if(a[i])
        {
          printf("    %c = %d\n",i-1+'a',num[i]);
        }
     }

   }
return 0 ;
}
View Code

 

转载于:https://www.cnblogs.com/zyue/archive/2013/05/21/3091871.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值