با استفاده از الگوریتم ارزیابی عبارات ریاضی، میتوان این سوال را حل کرد.
برای این کار، میتوانیم رشته ورودی را به عنوان ورودی به یک تابع بدهیم که با استفاده از یک پشته، عبارات ریاضی را از اعمال عملگرها به ترتیب اعمال کند و حاصل را در پایان با دقت دو رقم اعشار چاپ کند.
کد مربوط به این سوال، به صورت زیر است:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
struct Stack {
double items[10000];
int top;
};
typedef struct Stack stack;
void initialize(stack *s) {
s->top = -1;
}
int is_empty(stack *s) {
return s->top == -1;
}
int is_full(stack *s) {
return s->top == 9999;
}
void push(stack *s, double value) {
if (is_full(s)) {
printf("Stack is full.\n");
} else {
s->top++;
s->items[s->top] = value;
}
}
double pop(stack *s) {
if (is_empty(s)) {
printf("Stack is empty.\n");
return -1;
} else {
double value = s->items[s->top];
s->top--;
return value;
}
}
double peek(stack *s) {
return s->items[s->top];
}
int is_operator(char ch) {
return ch == '+' || ch == '-' || ch == '*' || ch == '/';
}
int precedence(char op) {
switch(op) {
case '*':
case '/':
return 2;
case '+':
case '-':
return 1;
default:
return 0;
}
}
double apply_operation(double left_operand, double right_operand, char op) {
switch(op) {
case '*': return left_operand * right_operand;
case '/': return left_operand / right_operand;
case '+': return left_operand + right_operand;
case '-': return left_operand - right_operand;
default: return 0;
}
}
double evaluate_expression(char *expression) {
stack values;
stack operators;
initialize(&values);
initialize(&operators);
for (int i = 0; i < strlen(expression); i++) {
char current_char = expression[i];
if (isspace(current_char)) {
continue;
} else if (isdigit(current_char) || current_char == '.') {
double value = atof(expression + i);
push(&values, value);
while (isdigit(expression[i]) || expression[i] == '.') {
i++;
}
i--;
} else if (current_char == '(') {
push(&operators, current_char);
} else if (current_char == ')') {
while (peek(&operators) != '(') {
char op = pop(&operators);
double right_operand = pop(&values);
double left_operand = pop(&values);
double result = apply_operation(left_operand, right_operand, op);
push(&values, result);
}
pop(&operators); // pop the '('
} else if (is_operator(current_char)) {
while (!is_empty(&operators) && precedence(current_char) <= precedence(peek(&operators))) {
char op = pop(&operators);
double right_operand = pop(&values);
double left_operand = pop(&values);
double result = apply_operation(left_operand, right_operand, op);
push(&values, result);
}
push(&operators, current_char);
}
}
while (!is_empty(&operators)) {
char op = pop(&operators);
double right_operand = pop(&values);
double left_operand = pop(&values);
double result = apply_operation(left_operand, right_operand, op);
push(&values, result);
}
return peek(&values);
}
int main() {
char expression[10001];
fgets(expression, 10001, stdin);
printf("%.2f", evaluate_expression(expression));
return 0;
}