https://pintia.cn/problem-sets/1112639514090356736/problems/1112639623511359511
这道题貌似是用递归,大致思路:
double getOp(){
string str;
if(str == "+")
return getOp() + getOp();
else if(str == "-")
return getOp() - getOp();
else if(str == "*")
return getOp() * getOp();
else if(str == "/"){
double a = getOp(), b = getOp();
if(b == 0) ERROR;//分母不为零
else return a / b;
}
else return atof(str);
//字符串转浮点数
//如果手写字符串转浮点数,注意 + - 和 .
}
而只懂后缀表达式的我对Stack有执念:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct node{
double key;
node *next = NULL;
};
typedef struct node * PtrToNode;
typedef PtrToNode Stack;
Stack creatStack();
void push(Stack s, double t);
bool IsEmpty(Stack s);
void pop(Stack s);
double top(Stack s);
double ToNumber(char s[]);
int check(Stack s);
int main()
{
char s[50][50];
int i = 0;
while(scanf("%s", s[i]) != EOF) i++;
Stack S = creatStack();
while(i--){
if(s[i][0] == '+' && strlen(s[i]) == 1){
if(!check(S)) return 0;
double a = top(S); pop(S);
if(!check(S)) return 0;
double b = top(S); pop(S);
push(S, a + b);
}
else if(s[i][0] == '-' && strlen(s[i]) == 1){
if(!check(S)) return 0;
double a = top(S); pop(S);
if(!check(S)) return 0;
double b = top(S); pop(S);
push(S, a - b);
}
else if(s[i][0] == '*'){
if(!check(S)) return 0;
double a = top(S); pop(S);
if(!check(S)) return 0;
double b = top(S); pop(S);
push(S, a * b);
}
else if(s[i][0] == '/'){
if(!check(S)) return 0;
double a = top(S); pop(S);
if(!check(S)) return 0;
double b = top(S); pop(S);
if(b == 0){//分母不为零
printf("ERROR");
return 0;
}
push(S, a / b);
}
else push(S, ToNumber(s[i]));
}
if(!check(S)) return 0;
if(S -> next -> next != NULL) printf("ERROR");
else printf("%.1lf", top(S));
return 0;
}
Stack creatStack(){
Stack s = (Stack)malloc(sizeof(Stack));
//while(!IsEmpty(s)) pop(s);
s -> next = NULL;
return s;
}
void push(Stack s, double t){
PtrToNode temp = (Stack)malloc(sizeof(Stack));
temp -> key = t;
temp -> next = s -> next;
s -> next = temp;
}
bool IsEmpty(Stack s){
return s -> next == NULL;
}
void pop(Stack s){
PtrToNode first = s -> next;
s -> next = s -> next -> next;
free(first);
}
double top(Stack s){
return s -> next -> key;
}
double ToNumber(char s[]){
double sum = 0;
int len = strlen(s), i = 0, mark = 1;
if(s[0] == '-'){
mark = -1; i = 1;
}
if(s[0] == '+'){
mark = 1; i = 1;
}//zz正号
while(i < len && s[i] != '.'){
sum = sum * 10 + s[i] - '0';
i++;
}
if(i == len) return sum * mark;
else{//小数点真有趣
i++;
double p = 10.0;
while(i < len){
sum = sum + (s[i] - '0') / p;
p = p * 10.0;
i++;
}
}
return sum * mark;
}
int check(Stack s){
if(IsEmpty(s)){
printf("ERROR");
return 0;
}
return 1;
}
正负号,小数点,分母不为零。。。真TM坑(手动黑脸
但AC也是贼jb爽啊hhhhhhh