首页 > 编程语言 > 详细

c语言实现逆波兰表达式!

时间:2021-03-15 19:22:17      阅读:28      评论:0      收藏:0      [点我收藏+]

C语言实现逆波兰表达式(栈的应用)

 #include<iostream>
 #include<cstdio>
 using namespace std;
 const int MAXSIZE = 110;
 char a[MAXSIZE];
 double operNum[MAXSIZE];
 ?
 double getSum(int* i){//地址传递,可以在边求值时边改变i的原值。如若是值传递,会导致值的重复算
  double sum = 0.0;
  int k = 0;
  while(a[*i] >= ‘0‘ && a[*i] <= ‘9‘){
  sum = sum * 10 + a[*i] - ‘0‘;
  (*i)++;
  }
  if(a[*i] == ‘.‘){
  (*i)++;
  while(a[*i] >= ‘0‘ && a[*i] <= ‘9‘){
  sum = sum * 10 + a[*i] - ‘0‘;
  (*i)++;
  k++;
  }
  }
  while(k!=0){
  sum /= 10;
  k--;
  }
  return sum;
 }
 int main(){
  gets(a);//这样可以读入空格,要求以‘#‘结尾
 
  int i=0;
  int top=0;
  double x1,x2;
  while (a[i] != ‘#‘){
  if(a[i] >= ‘0‘ && a[i] <= ‘9‘){
  double f = getSum(&i);
  operNum[top++] = f;
  }else if(a[i] == ‘ ‘){
  i++;
  }else if(a[i] == ‘+‘){
  x1 = operNum[--top];
  x2 = operNum[--top];
  operNum[top++] = x1 + x2;
  i++;
  }else if(a[i] == ‘-‘){
  x1 = operNum[--top];
  x2 = operNum[--top];
  operNum[top++] = x2 - x1;
  i++;
  }else if(a[i] == ‘*‘){
  x1 = operNum[--top];
  x2 = operNum[--top];
  operNum[top++] = x1 * x2;
  i++;
  }else if(a[i] == ‘/‘){
  x1 = operNum[--top];
  x2 = operNum[--top];
  operNum[top++] = x2 / x1;
  i++;
  }
  }
 
  cout<<operNum[0]<<endl;
  return 0;
 }

技术分享图片

 

c语言实现逆波兰表达式!

原文:https://www.cnblogs.com/yuanshixiao/p/14538351.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!