Chinaunix首页 | 论坛 | 博客
  • 博客访问: 772592
  • 博文数量: 230
  • 博客积分: 6330
  • 博客等级: 准将
  • 技术积分: 2188
  • 用 户 组: 普通用户
  • 注册时间: 2009-07-10 15:55
个人简介

脚踏实地

文章分类

全部博文(230)

文章存档

2017年(1)

2016年(7)

2015年(10)

2014年(32)

2013年(24)

2012年(33)

2011年(50)

2010年(30)

2009年(43)

分类: C/C++

2011-06-07 23:00:05

  1. #include "stdafx.h"
  2. #include "stdio.h"
  3. #include "stdlib.h"
  4. #include <iostream>
  5. using namespace std;

  6. /* 原则: 加减符号 只能决定左侧的单元该不该被结算,
  7.   * 右侧的值不确定是不是单独的计算元素还是由乘除组合的单元 */
  8. int compute(char* str)
  9. {
  10.     int length_str = strlen(str);
  11.     char* tmp = str;
  12.     /* preLocation: 前一个数字起始的位置,
  13.      * endFlag: 最后一个运算符 [1, 代表加减,直接结束 0代表乘除]
  14.      * tmpLeft tmpRight 表示乘除运算符左右侧的数字*/
  15.     int preLocation = 0, tmpLeft=0, tmpRight=0;
  16.     bool endFlag = 1;
  17.     int i=1;
  18.     int ret = 0; //最终结果

  19.     while ( i<length_str)
  20.     {
  21.         if ('+' == tmp[i] ||
  22.             '-' == tmp[i])
  23.         {
  24.             if (endFlag)/*元素结算*/
  25.             {
  26.                 ret += atoi(&str[preLocation]);
  27.             }
  28.             else/*乘除单元结算*/
  29.             {
  30.                 ret += tmpLeft;
  31.             }
  32.             preLocation = i;
  33.             ++i;
  34.             endFlag=1;
  35.         }
  36.         else if ('*' == tmp[i])
  37.         {
  38.             tmpLeft = atoi(&str[preLocation]);
  39.             tmpRight = atoi(&str[i+1]);
  40.             tmpLeft *= tmpRight;
  41.             preLocation = ++i;
  42.             endFlag = 0;
  43.         }
  44.         else if ( '/' == tmp[i])
  45.         {
  46.             tmpLeft = atoi(&str[preLocation]);
  47.             tmpRight = atoi(&str[i+1]);
  48.             tmpLeft /= tmpRight;
  49.             preLocation = ++i;
  50.             endFlag = 0;
  51.         }
  52.         while ('0'<= str[i] &&
  53.             '9'>= str[i])
  54.         {
  55.             ++i;
  56.             if ( i == length_str)
  57.             {
  58.                 return (endFlag?(ret+atoi(&str[preLocation])) :(ret+tmpLeft));
  59.             }
  60.         }
  61.     }
  62.     return 0x7fffffff;//表示出错
  63. }



  64. void main(){
  65.     char buff[128];
  66.     printf("请输入运算表达式:\n");
  67.     scanf("%s", &buff);
  68.     printf("结果为: %d\n", compute(buff));
  69.     return;
  70. }
阅读(1589) | 评论(0) | 转发(0) |
0

上一篇:零距离美语会话

下一篇:Voip相关

给主人留下些什么吧!~~