简单计算器

来源:互联网 发布:wifi探针 mac 编辑:程序博客网 时间:2024/06/06 00:18
A - 简单计算器

Crawling in process...Crawling failedTime Limit:1000MS    Memory Limit:32768KB    64bit IO Format:%I64d & %I64u

SubmitStatus

 

Description

读入一个只包含 +, -, *, / 的非负整数计算表达式,计算该表达式的值。       
 

Input

测试输入包含若干测试用例,每个测试用例占一行,每行不超过200个字符,整数和运算符之间用一个空格分隔。没有非法表达式。当一行中只有0时输入结束,相应的结果不要输出。       
       

Output

对每个测试用例输出1行,即该表达式的值,精确到小数点后2位。       
       

Sample Input

1 + 24 + 2 * 5 - 7 / 110
              

Sample Output

3.0013.36

 

 

代码一:

#include <iostream>#include <stdio.h>#include <vector>#include <stack>#include <queue>#include <algorithm>#include <string.h>using namespace std;char e[250],post[250];stack<char>Op;bool Isnum(char c){if(c>='0'&&c<='9')    return true;    return false;}int OPMode(char c){if(c=='+')  return 1;if(c=='-')  return 2;if(c=='*')  return 3;if(c=='/')  return 4; return -1;}void SplitExp(char* s){int i,j=0;memset(post,'\0',sizeof(post)); for(i=0;i<strlen(s);i++){if(s[i]==' ') continue;  post[j++]=' ';  while(Isnum(s[i]))   post[j++]=s[i++];  int curop=OPMode(s[i]);  if(curop!=-1)  {   if(curop<=2)   {   while(!Op.empty())    {     post[j++]=Op.top();     Op.pop();    }   }   else   {while(!Op.empty()&&OPMode(Op.top())>2)    {     post[j++]=Op.top();     Op.pop();    }   }   Op.push(s[i]);}}while(!Op.empty()){post[j++]=Op.top();Op.pop();}}stack<double>Num;double Cal(){while(!Num.empty())Num.pop();int i=0,j;int len=strlen(post);while (i++<len){if(post[i]==' ')continue;  double cur=0;  bool hasnum=false;  while (Isnum(post[i]))  {   cur*=10;   cur+=post[i++]-'0';   hasnum=true;  }  if(hasnum)  Num.push(cur);  if(OPMode(post[i])!=-1)  {   double num1=Num.top();   Num.pop();   double num2=Num.top();   Num.pop();   switch(post[i])   {   case '+':  Num.push(num2+num1);break;   case '-':  Num.push(num2-num1);break;   case '*':  Num.push(num2*num1);break;   case '/':  Num.push(num2/num1);break;   }  } }return Num.top();}int main(){while(gets(e)) {int len1 = strlen(e);  if(e[0]=='0'&&len1==1)   break;  SplitExp(e);  printf("%.2f\n",Cal());}return 0;}


 

代码二:

#include <stdio.h>#include <stack>#include <algorithm>using namespace std;int main(){double n,m; char c; while(scanf("%lf",&n) != EOF) {  c=getchar();  if(c=='\n' &&n==0)   break;  stack<double>s;  s.push(n);  scanf("%c",&c);  while (scanf("%lf", &n) != EOF)  {    if(c=='*')   {    m=s.top();    m*=n;    s.pop();    s.push(m);   }   if(c=='/')   {    m=s.top();    m/=n;    s.pop();    s.push(m);   }   if(c=='+') s.push(n);   if(c=='-') s.push(0-n);   if(getchar()=='\n') break;            c=getchar();}  double sum=0;  while(!s.empty())  {   sum+=s.top();   s.pop();  }  printf("%.2lf\n",sum); } return 0;}


0 0
原创粉丝点击