首先上代码
#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;
float ans=0,minuss=0;
char change;
int main()
{
string count;
cin>>count;
int number=0;
int numberyn=-1;
int pn=1;
int equ=1;
for(int i=0;i<count.size();i++)
{
if(count[i]-'0'>=0&&count[i]-'0'<10)
{
if(numberyn==-1)
{
numberyn=1;
}
number*=10;
number+=count[i]-'0';
continue;
}
if(count[i]=='+')
{
if(numberyn==1)
{
ans+=number*(-equ)*pn;
number=0;
numberyn=-1;
}
pn=1;
continue;
}
if(count[i]=='-')
{
if(numberyn==1)
{
ans+=number*(-equ)*pn;
number=0;
numberyn=-1;
}
pn=-1;
continue;
}
if(count[i]=='=')
{
if(numberyn==1)
{
ans+=number*(-equ)*pn;
number=0;
numberyn=-1;
}
equ=-1;
pn=1;
continue;
}
if(count[i]-'a'>=0&&count[i]-'a'<=25)
{
change=count[i];
if(number==0)//这个也没想到啊
{
number=1;
}
minuss+=number*equ*pn;
numberyn=-1;
number=0;
continue;
}
}
if(number>0)
{
ans+=number*pn;
}
float x;
x=ans/minuss;
cout<<change<<'=';
if(ans==0&&minuss<0)//坑死啦
{
x=-x;
}
printf("%.3f",x);
return 0;
}
1. x
变量前无指数,则应默认为1.
if(number==0)
{
number=1;
}
2. 0除以负数 结果为-0
所以要加特判。
if(ans==0&&minuss<0)
{
x=-x;
}