90 #10WA不知道错哪了感觉是负数但好像又不是
查看原帖
90 #10WA不知道错哪了感觉是负数但好像又不是
1060116
CoLlECToRs楼主2023/9/19 00:42
#define _CRT_SECURE_NO_WARNINGS 1
#include<bits/stdc++.h>
using namespace std;
stack<char>op, dat, out, dat1;
stack<int>cal,dat2;
char s[105];
int op_priority(char s);
int calc(char opera, int a, int b);

int main() {
	scanf("%s", s);
	//转换为后缀表达式
	int length = strlen(s);
	for (int i = 0; i < length; i++) {
		int n = op_priority(s[i]);
		if (!n) {
			dat.push(s[i]);
		}
		else {
			if (op.empty() || op.top() == '(') {
				op.push(s[i]); continue;
			}
			if (n == 4 && op.top() == '^') {
				op.push(s[i]); continue;
			}
			if (s[i] == ')') {
				while (op.top() != '(') {
					dat.push(op.top());
					op.pop();
				}
				op.pop();continue;
			}
			while (!op.empty() && op.top() != '(' && n <= op_priority(op.top())) {
				dat.push(op.top());
				op.pop();
			}
			op.push(s[i]);
		}
	}
	while (!op.empty()) {
		dat.push(op.top());
		op.pop();
	}
	//逆序输出后缀表达式
	while (!dat.empty()) {
		out.push(dat.top());
		dat1.push(dat.top());
		dat.pop();
	}
	while (!out.empty()) {
		printf("%c ", out.top());
		out.pop();
	}
	printf("\n");

	//计算结果
	while (!dat1.empty()) {
		while (op_priority(dat1.top()) == 0) {
			cal.push(dat1.top() - '0');
			dat1.pop();
		}
		char opera = dat1.top();
		dat1.pop();
		int a = cal.top();
		cal.pop();
		int b = cal.top();
		cal.pop();
		int result = calc(opera, a, b);
		cal.push(result);
		while (!cal.empty()) {
			dat2.push(cal.top());
			cal.pop();
		}
		while (!dat2.empty()) {
			printf("%d ", dat2.top());
			cal.push(dat2.top());
			dat2.pop();
		}
		while (!dat1.empty()) {
			printf("%c ", dat1.top());
			dat.push(dat1.top());
			dat1.pop();
		}
		while (!dat.empty()) {
			dat1.push(dat.top());
			dat.pop();
		}
		printf("\n");
	}
	return 0;
}

int op_priority(char s) {
	switch (s) 
	{
	case '+':return 1;
		break;
	case '-':return 1;
		break;
	case '*':return 2;
		break;
	case '/':return 2;
		break;
	case '(':return 3;
		break;
	case ')':return 3;
		break;
	case '^':return 4;
		break;
	default:
		return 0;
	}
}


int calc(char opera, int b, int a) {
	switch (opera)
	{
	case '+':return a + b;
		break;
	case '-':return a - b;
		break;
	case '*':return a * b;
		break;
	case '/':return a / b;
		break;
	case '(':return 3;
		break;
	case ')':return 3;
		break;
	case '^':return pow(a,b);
		break;
	default:
		return 0;
	}
}
2023/9/19 00:42
加载中...