簡易計算機プログラム
1840 ワード
/*
/* ,
/* :1.
/* 2. BUG
/* 3. */
/* */
#include<stdio.h>
#include<ctype.h>
#include<stack>
using namespace std;
stack<char> s;
stack<int> s2;
int calculate_mark(char a); //
void calculate(char *p); //
void calculate_stack(char b); //
int calculate_mark(char a)
{
switch(a)
{
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
case '(':
return 3;
default:
{
printf(" !");
exit(1);
}
}
}
void calculate_stack(char b)
{
int num1,num2,num3;
num1=s2.top();
s2.pop();
num2=s2.top();
s2.pop();
if(b=='+')
num3=num1+num2;
else if(b=='-')
num3=num2-num1;
else if(b=='*')
num3=num1*num2;
else if(b=='/')
num3=num2/num1;
s2.push(num3);
}
void calculate(char *p)
{
while(*p)
{
if(isdigit(*p))
s2.push(*p-'0');
else
{
if(s.empty())
s.push(*p);
else if(*p==')')
{
while(s.top()!='(')
{
calculate_stack(s.top());
s.pop();
}
s.pop();
}
else if(*p=='(')
{
s.push(*p);
}
else if(calculate_mark(s.top())<calculate_mark(*p))
s.push(*p);
else if(calculate_mark(s.top())>=calculate_mark(*p))
{
while(!s.empty()&&s.top()!='('&&calculate_mark(s.top())>=calculate_mark(*p))
{
calculate_stack(s.top());
s.pop();
}
s.push(*p);
}
}
p++;
}
while(!s.empty())
{
calculate_stack(s.top());
s.pop();
}
}
int main()
{
char *p="3*(6+1)-4/2+6";
calculate(p);
printf("%d
",s2.top());
return 0;
}