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语言实现逆波兰表达式!


基础教程推荐
猜你喜欢
- C/C++编程中const的使用详解 2023-03-26
- 如何C++使用模板特化功能 2023-03-05
- C++使用easyX库实现三星环绕效果流程详解 2023-06-26
- C语言 structural body结构体详解用法 2022-12-06
- C++中的atoi 函数简介 2023-01-05
- C利用语言实现数据结构之队列 2022-11-22
- C++详细实现完整图书管理功能 2023-04-04
- C语言基础全局变量与局部变量教程详解 2022-12-31
- 详解c# Emit技术 2023-03-25
- 一文带你了解C++中的字符替换方法 2023-07-20