a017.
五則運算
| From: [125.226.226.101] |
發表日期
:
2012-12-10 22:53
#include<stdio.h>
#include<stdlib.h>
#include<iostream>
using namespace std;
void inToPostfix();
int priority(char);
void clear();
int convert();
int calculator(char, int, int);
char infix[1000] = {'\0'};
char postfix[1000] = {'\0'};
int stack[1000] = {'\0'};
int main(void){
while(cin.getline(infix, 1000)){
inToPostfix();
printf("%d\n", convert());
clear();
}
return 0;
}
void inToPostfix(){
char stack[1000] = {'\0'};
int top = 0, index = 0;
for(int i = 0; infix[i] != '\0'; i++){
switch(infix[i]){
case '(':
stack[++top] = infix[i];
break;
case '+': case '-': case '*': case '/' : case '%':
while(priority(stack[top]) >= priority(infix[i])){
postfix[index++] = stack[top--];
}
stack[++top] = infix[i];
break;
case ')':
while(stack[top] != '('){
postfix[index++] = stack[top--];
}
top--;
break;
case ' ':
break;
default:
postfix[index++] = infix[i];
}
}
while(top > 0)
postfix[index++] = stack[top--];
}
int priority(char op){
switch(op){
case '+': case '-':
return 1;
case '*': case '/': case '%':
return 2;
default:
return 0;
}
}
void clear(){
for(int i = 0; infix[i] != '\0'; i++)
infix[i] = '\0';
for(int i = 0; postfix[i] != '\0'; i++)
postfix[i] = '\0';
}
int convert(){
int top = 0, i = 0;
int sum = 0;
for(i; postfix[i] != '\0'; i++){
switch(postfix[i]){
case '+': case '-': case '*': case '/': case '%':
stack[top - 1] = calculator(postfix[i], stack[top - 1], stack[top]);
top--;
break;
default:
sum = sum * 10 + postfix[i] - '0';
stack[++top] = sum;
sum = 0;
break;
}
}
return stack[top];
}
int calculator(char op, int operand1, int operand2){
switch(op){
case '+':
return operand1 + operand2;
case '-':
return operand1 - operand2;
case '*':
return operand1 * operand2;
case '/':
return operand1 / operand2;
case '%':
return operand1 % operand2;
}
}