132 lines
3.4 KiB
C
132 lines
3.4 KiB
C
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
#include <math.h>
|
|
#include "calculator.h"
|
|
|
|
int precedence(char c){
|
|
if (c == 's' || c == 'c' || c == 'l' || c == '^') return 3;
|
|
if (c == '*' || c == '/') return 2;
|
|
if (c == '+' || c == '-') return 1;
|
|
return 0;
|
|
}
|
|
|
|
int is_operator(char c){
|
|
if (c == '+' || c == '-' || c == '*' || c == '/' || c == '^')
|
|
return 1;
|
|
return 0;
|
|
}
|
|
|
|
void infix_to_postfix(const char *infix, char *postfix){
|
|
char stack[MAX];
|
|
int top = -1;
|
|
int i = 0, k = 0;
|
|
|
|
while (infix[i] != '\0') {
|
|
|
|
if ((infix[i] >= '0' && infix[i] <= '9') || infix[i] == '.'){
|
|
postfix[k++] = infix[i++];
|
|
}
|
|
else if (infix[i] == ' '){
|
|
postfix[k++] = ' ';
|
|
i++;
|
|
}
|
|
else if (strncmp(&infix[i], "sin", 3) == 0){
|
|
stack[++top] = 's';
|
|
i += 3;
|
|
}
|
|
else if (strncmp(&infix[i], "cos", 3) == 0){
|
|
stack[++top] = 'c';
|
|
i += 3;
|
|
}
|
|
else if (strncmp(&infix[i], "log", 3) == 0){
|
|
stack[++top] = 'l';
|
|
i += 3;
|
|
}
|
|
else if (infix[i] == '('){
|
|
stack[++top] = '(';
|
|
i++;
|
|
}
|
|
else if (infix[i] == ')'){
|
|
while (top >= 0 && stack[top] != '('){
|
|
postfix[k++] = ' ';
|
|
postfix[k++] = stack[top--];
|
|
}
|
|
top--;
|
|
if (top >= 0 && (stack[top] == 's' || stack[top] == 'c' || stack[top] == 'l')){
|
|
postfix[k++] = ' ';
|
|
postfix[k++] = stack[top--];
|
|
}
|
|
i++;
|
|
}
|
|
else if (is_operator(infix[i])){
|
|
postfix[k++] = ' ';
|
|
while (top >= 0 && precedence(stack[top]) >= precedence(infix[i])){
|
|
postfix[k++] = stack[top--];
|
|
postfix[k++] = ' ';
|
|
}
|
|
stack[++top] = infix[i++];
|
|
}
|
|
else {
|
|
i++;
|
|
}
|
|
}
|
|
|
|
while (top >= 0) {
|
|
postfix[k++] = ' ';
|
|
postfix[k++] = stack[top--];
|
|
}
|
|
|
|
postfix[k] = '\0';
|
|
}
|
|
|
|
double evaluate_postfix(const char *postfix) {
|
|
double stack[MAX];
|
|
int top = -1;
|
|
int i = 0;
|
|
char num[MAX];
|
|
|
|
while (postfix[i] != '\0') {
|
|
|
|
if (postfix[i] == ' ') {
|
|
i++;
|
|
continue;
|
|
}
|
|
|
|
if ((postfix[i] >= '0' && postfix[i] <= '9') || postfix[i] == '.') {
|
|
int j = 0;
|
|
while ((postfix[i] >= '0' && postfix[i] <= '9') || postfix[i] == '.') {
|
|
num[j++] = postfix[i++];
|
|
}
|
|
num[j] = '\0';
|
|
stack[++top] = atof(num);
|
|
}
|
|
else {
|
|
if (postfix[i] == 's') {
|
|
stack[top] = sin(stack[top]);
|
|
}
|
|
else if (postfix[i] == 'c') {
|
|
stack[top] = cos(stack[top]);
|
|
}
|
|
else if (postfix[i] == 'l') {
|
|
stack[top] = log(stack[top]);
|
|
}
|
|
else if (postfix[i] == '^'){
|
|
stack[top] = stack[top] * stack[top];
|
|
}
|
|
else{
|
|
double b = stack[top--];
|
|
double a = stack[top--];
|
|
|
|
if (postfix[i] == '+') stack[++top] = a + b;
|
|
if (postfix[i] == '-') stack[++top] = a - b;
|
|
if (postfix[i] == '*') stack[++top] = a * b;
|
|
if (postfix[i] == '/') stack[++top] = a / b;
|
|
}
|
|
i++;
|
|
}
|
|
}
|
|
return stack[top];
|
|
}
|
|
|