#include<stdio.h>
#include<stack>
#include<string>
#include<iostream>
using namespace std;
stack<int> s;
stack<double> p;
stack<int> j;
char input[100];
int mat[8] = { 0,1,2,2,3,3,3,4 };
int out[8] = { 0,4,2,2,3,3,3,1 };
void getop(bool &judge, int &retn, int &i)
{
if (i == 0 && s.empty() == true)
{
judge = true;
retn = 0;
return;
}
if (input[i] == 0)
{
judge = true;
retn = 0;
return;
}
if (input[i] >= '0'&&input[i] <= '9')
{
judge = false;
retn = 0;
for (; input[i] >= '0' && input[i] <= '9'; i++)
{
retn *= 10;
retn += input[i] - '0';
}
}
else
{
judge = true;
if (input[i] == '+')
retn = 2;
if (input[i] == '-')
retn = 3;
if (input[i] == '*')
retn = 4;
if (input[i] == '/')
retn = 5;
if (input[i] == '(')
retn = 7;
if (input[i] == ')')
retn = 1;
if (input[i] == '%')
retn = 6;
i++;
return;
}
if (input[i] == ' ')
i++;
return;
}
int judge()
{
int i, jud = 0;
int flag1 = 0, flag2 = 0;
for (i = 0; input[i] != 0; i++)
{
if (input[i] >= '0'&&input[i] <= '9')
{
if (flag1 == 1 && flag2 == 1)
{
jud = 1; break;
}
flag1 = 1;
}
else if (input[i] == ' ')
flag2 = 1;
else
{
flag1 = 0; flag2 = 0;
}
}
for (i = 0; input[i] != 0; i++)
{
if (input[i] == '(')
j.push(i);
if (input[i] == ')')
{
if (j.empty() == true)
{
jud = 2; break;
}
else
j.pop();
}
}
if (!j.empty())
jud = 2;
while (!j.empty())
j.pop();
return jud;
}
int main()
{
while (gets_s(input))
{
int x = judge();
if (x == 1)
printf("两个数字之间缺省运算符\n");
else if (x == 2)
printf("缺省括号\n");
else
{
bool judge; int retn;
int index = 0;
while (!s.empty())
s.pop();
while (!p.empty())
p.pop();
while (true)
{
getop(judge, retn, index);
if (judge == false)
p.push((double)retn);
else
{
double temp;
if (s.empty() == true || mat[retn] > out[s.top()])
s.push(retn);
else
{
while (mat[retn] <= out[s.top()] && s.top() != 7 && s.top() != 0)
{
int cal_fu = s.top();
s.pop();
double a = p.top();
p.pop();
double b = p.top();
p.pop();
if (cal_fu == 2)
temp = b + a;
if (cal_fu == 3)
temp = b - a;
if (cal_fu == 4)
temp = b * a;
if (cal_fu == 5)
temp = b / a;
if (cal_fu == 6)
temp = (int)b % (int)a;
p.push(temp);
}
if (retn == 1)
s.pop();
else
s.push(retn);
}
}
if (s.size() == 2 && s.top() == 0)
break;
}
printf("%.2f\n", p.top());
}
}
return 0;
}
计算器....
最新推荐文章于 2023-09-18 09:54:05 发布