Data_Structure/作業/unit5/try_DS5.cpp
2025-01-20 21:30:53 +08:00

118 lines
3.1 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include <math.h>
#include <stdio.h>
#include <stdlib.h>
int priority(char op) {
switch(op) {
case '+' : case '-' : return 1;
case '*' : case '/' : case '%' : return 2;
case '^' : return 3;
default : return 0;
}
}
void printf_postfix(char str[105][10], int len) {
int i = 0;
for (i = 0; i < len; i++) {
if (str[i][0] != '0') printf("%s ", str[i]);
}
printf("\n");
}
double cal(char op, double p1, double p2) {
switch(op) {
case '+' : return p1 + p2;
case '-' : return p1 - p2;
case '*' : return p1 * p2;
case '/' : return p1 / p2;
case '%' : return (int)p1 % (int)p2;
case '^' : return pow(p1, p2);
}
}
void oper(char str[105][10], int len) {
double now[105] = {0.0};
int L = 0, top = 0;
while (L < len) {
switch(str[L][0]) {
case '+' : case '-' : case '*' : case '/' : case '%' : case '^' :
now[top-1] = cal(str[L][0], now[top-1], now[top]);
top--;
break;
default :
now[++top] = atof(str[L]);
}
L++;
}
printf("\nšBşâľ˛ŞG=%5f\n\n", now[top]);
}
void infix_to_postfix(char* str) {
char infix[105][10] = {' '}, stack[105], now[10];
int L = 0, R = 0, top = 0, i, j, flag = 0;
while (str[L] != '\0') {
switch(str[L]) {
case '(' :
stack[++top] = str[L];
if (str[L+1] == '-') { flag = 1; L++; }
break;
case ')' :
while (stack[top] != '(') {
infix[R++][0] = stack[top--];
}
top--;
break;
case '+' : case '-' : case '*' : case '/' : case '%' : case '^' :
while (priority(stack[top]) >= priority(str[L])) {
infix[R++][0] = stack[top--];
}
stack[++top] = str[L];
if (str[L+1] == '-') { flag = 1; L++; }
break;
default :
i = 0;
while (str[L] == '.' || (str[L] >= '0' && str[L] <= '9')) {
now[i++] = str[L++];
}
if (flag) {
infix[R][0] = '0'; infix[R+2][0] = '-'; flag = 0;
for (j = 0; j < i; j++) infix[R+1][j] = now[j];
R += 2;
} else {
for (j = 0; j < i; j++) infix[R][j] = now[j];
}
L--; R++;
}
L++;
}
while (top) {
infix[R++][0] = stack[top--];
}
printf_postfix(infix, R);
oper(infix, R);
}
int main() {
printf("%5f", 1+sin((-50.2+sin(3.8*20)*cos(-30-100%40))*pow(2, -2.5))*cos(123.456));
char str[105] = {'\0'};
while (printf("żé¤J¤¤§ÇŚĄ(¤ä´Š+ - * / ^ () sin() cos()šBşâ) => ")) {
scanf("%s", str);
printf("\nšďŔłŞşŤá§ÇŚĄĄG");
infix_to_postfix(str);
}
return 0;
}
/*
10+20*(50-30)/2^4-6*8
10.5+20.8*(50.1-30.6)/2.5^4-6.6*8.2
10-30*(-40-20)%2^4+7.5*-6
1+sin((-50.2+sin(3.8*20)*cos(-30-100%40))*2^-2.5)*cos(123.456)
*/