读书人

小数点的计算有关问题

发布时间: 2012-09-28 00:03:35 作者: rapoo

小数点的计算问题
最近在做OJ,有个表达式的问题,写了一天的时间吧

#include<iostream>
#include<sstream>
#include<string>
#include<cstring>
#include<iomanip>
#include<stack>
using namespace std;
char compare(char c,char d) //比较优先级
{
switch(c)
{
case '+':
case '-':if(d=='+'||d=='-'||d==')'||d=='=') return '>';else return '<';break;
case '*':
case '/':if(d=='+'||d=='-'||d=='*'||d=='/'||d==')'||d=='=') return '>';else return '<';break;
case '(':if(d==')') return '='; if(d=='=') return '>';else return '<';break;
case ')':if(d=='(') return '='; return '>';break;
case '=':if(d=='=') return '='; else return '<';break;
}
}
//字符串转换为double
double To(char a[])
{
stringstream oss;
oss<<a;
double result;
oss>>result;
return result;
}
bool ischar(char c)
{
if(c=='+'||c=='-'||c=='*'||c=='/'||c=='=') return true;
return false;
}
void change(char mid[],char post[])
{
stack<char> s1;
char a[1000];
s1.push('=');
int i=0,m=-1,l=strlen(mid);
while(i<l)
{
char ch;
if((mid[i]>='0'&&mid[i]<='9')||(mid[i]=='.'))
{
post[++m]=mid[i];
i++;
}
else
{
post[++m]=' ';
if(compare(s1.top(),mid[i])=='<') { s1.push(mid[i]);i++;}
else if(compare(s1.top(),mid[i])=='>') { ch=s1.top();s1.pop();post[++m]=ch;}
else if(compare(s1.top(),mid[i])=='=') { s1.pop();++i;}
}
}
}
double Operator(double a,char b,double c)
{
if(b=='+') return a+c;
if(b=='-') return a-c;
if(b=='*') return a*c;
if(b=='/') return a/c;
}
double run(char post[])
{
int l=strlen(post);
int i=0,flag=0;
stack<double> str;
char q[5]=" ";
int j=-1;
double result,x,y;
while(i<l)
{
if((post[i]>='0'&&post[i]<='9')||(post[i]=='.'))
{
q[++j]=post[i];
flag=1;
++i;
}
else
{
if(flag==1) { result=To(q);flag=0;j=-1;str.push(result);}
if(post[i]==' ') ++i;
if(ischar(post[i]))
{
x=str.top();str.pop(); y=str.top(); str.pop();
str.push(Operator(y,post[i],x));++i;
}
}
}
return str.top();
}
int main()
{
int n;
cin>>n;
while(n--)
{
char mid[100],post[100]={'0'};
cin>>mid;
change(mid,post);
cout<<setiosflags(ios::fixed)<<setprecision(2)<<run(post)<<endl;

}
system("pause");
return 0;
}
计算时只要带小数的 比如 1.1+2= 会出现计算错误,但 1.00+1=之类的不会出错,实在看不出代码错在哪里了,求助!

[解决办法]

C/C++ code
double run(char post[]){  int l=strlen(post);  int i=0,flag=0;  stack<double> str;  char q[5]=" ";  int j=-1;  double result,x,y;  while(i<l)  {  if((post[i]>='0'&&post[i]<='9')||(post[i]=='.'))  {  q[++j]=post[i];  flag=1;  ++i;  }  else  {  if(flag==1) { [color=#FF0000]q[j + 1] = '\0';//这里q清0[/color]result=To(q);flag=0;j=-1;str.push(result);}  if(post[i]==' ') ++i;  if(ischar(post[i]))  {  x=str.top();str.pop(); y=str.top(); str.pop();  str.push(Operator(y,post[i],x));++i;  }  }  }  return str.top();} 

读书人网 >C++

热点推荐