C语言实现逆波兰表达式(栈的应用) #includeiostream #includecstdio using namespace std; const int MAXSIZE = 110; char a[MAXSIZE]; double operNum[MAXSIZE]; ? double getSum(int* i){//地址传递,可以在边...
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语言实现逆波兰表达式!
猜你喜欢
- Qt计时器使用方法详解 2023-05-30
- C语言手把手带你掌握带头双向循环链表 2023-04-03
- C语言详解float类型在内存中的存储方式 2023-03-27
- C语言qsort()函数的使用方法详解 2023-04-26
- Easyx实现扫雷游戏 2023-02-06
- ubuntu下C/C++获取剩余内存 2023-09-18
- C++ 数据结构超详细讲解顺序表 2023-03-25
- 详解C语言中sizeof如何在自定义函数中正常工作 2023-04-09
- 我应该为我的项目使用相对包含路径,还是将包含目录放在包含路径上? 2022-10-30
- c++ const 成员函数,返回一个 const 指针.但是返回的指针是什么类型的 const? 2022-10-11
