简单计算器
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 25351 Accepted Submission(s): 9180
思路:运算符号无非乘除优先级大于加减,只要把加减压入栈内,乘除直接计算,题目本身很简单,主要是需要注意的地方有3点:
1、0 + 2 + ......是否可求
2、0 输出0
3、数字可以是多位(样例已给)
代码:(写的有点杂,将就看)
#include<cstdio>
#include<cstring>
#include<stack>
using namespace std;
char str[305];
bool isdigit(char ch)
{
if (ch >= '0' && ch <= '9')
return true;
return false;
}
int main()
{
while (gets(str) && strcmp(str,"0") != 0)
{
double ans = 0,ty;
stack<double> s1;
stack<char> s2;
int len = strlen(str),i;
for (i = 0;i < len;i ++)
{
bool flag = false;
ty = 0;
while (isdigit(str[i]))
{
ty = ty * 10 + (str[i] - '0');
i ++;
flag = true;
}
if (flag)
{
s1.push(ty);
continue;
}
if (str[i] == ' ') continue;
else
{
if (str[i] == '*')
{
i ++;
while (str[i] == ' ') i ++;
double x = 0;
while (isdigit(str[i]))
{
x = x * 10 + (str[i] - '0');
i ++;
}
ty = s1.top() * x;
s1.pop();
s1.push(ty);
}
else if (str[i] == '/')
{
i ++;
while (str[i] == ' ') i ++;
double x = 0;
while (isdigit(str[i]))
{
x = x * 10 + (str[i] - '0');
i ++;
}
ty = s1.top() / x;
s1.pop();s1.push(ty);
}
else
s2.push(str[i]);
}
}
while (!s2.empty())
{
if (s2.top() == '+')
{
ans += s1.top();s1.pop();
}
else
{
ans += - s1.top();s1.pop();
}
s2.pop();
}
ans += s1.top();
s1.pop();
printf("%.2lf\n",ans);
}
return 0;
}
本文介绍了一个简单的计算器程序的设计与实现过程,该程序能够处理包含加、减、乘、除运算的非负整数表达式,并准确计算其结果。文章详细解释了如何通过栈来管理运算符与操作数,以确保正确的运算优先级。
&spm=1001.2101.3001.5002&articleId=80615960&d=1&t=3&u=293346af34354d1ab373f5cca4c94a34)

被折叠的 条评论
为什么被折叠?



