题目大意:有字符串表示的一个四则运算表达式,要求计算出该表达式的正确数值。四则运算即:加减乘除"+-*/",另外该表达式中的数字只能是1位(数值范围0~9)。另若有不能整除的情况,按向下取整处理,eg: 8/3得出值为2。
若有字符串"8+7*2-9/3",计算出其值为19。
主要考点:
1. 数字的字符形式变换为数字形式的方法;
2. 数字的数字形式变换为数字的字符串形式的方法。
<span style="font-family: Arial, Helvetica, sans-serif;">#include <iostream></span>
#include <string>
using namespace std;
void cq(string& str)
{
int npos1,npos2,npos,result;
npos1=str.find("*");
npos2=str.find("/");
if(npos1<0 && npos2<0)
return;
if(npos1>0 && npos2>0) //乘除运算
{
npos= npos1<npos2 ? npos1:npos2;
}
else if(npos1<0 && npos2>0) //乘除运算
{
npos=npos2;
}
else if(npos1>0 && npos2<0) //乘除运算
{
npos=npos1;
}
int i=npos-1;
char temp[10];
int j=0;
while(i>=0 && str[i]>='0' && str[i]<='9')
{
temp[j++]=str[i];
temp[j]='\0';
i--;
}
//反转
int lent=strlen(temp);
for(int k=0;k<(lent+1)/2;k++)
{
int Temp=temp[k];
temp[k]=temp[lent-1-k];
temp[lent-1-k]=Temp;
}
int a=atoi(temp);
int pos=++i;//记录开始被替换的位置。
i=npos+1;
j=0;
while(i<str.length() && str[i]>='0' && str[i]<='9')
{
temp[j++]=str[i];
temp[j]='\0';
i++;
}
int b=atoi(temp);
//i为替换的结束的下一位置。
if(str[npos]=='*')
result=a*b;
else
result=a/b;
char r[5];
itoa(result,r,10);
string re=r;
str.replace(pos,i-pos,re);
npos1=str.find("*");
npos2=str.find("/");
if(npos1>0 || npos2>0)
cq(str);
}
void jj(string& str)
{
int npos1,npos2,npos,result;
npos1=str.find("+");
npos2=str.find("-");
if(npos1<0 && npos2<0)
return;
if(npos1>0 && npos2>0) //乘除运算
{
npos= npos1<npos2 ? npos1:npos2;
}
else if(npos1<0 && npos2>0) //乘除运算
{
npos=npos2;
}
else if(npos1>0 && npos2<0) //乘除运算
{
npos=npos1;
}
int i=npos-1;
char temp[10];
int j=0;
while(i>=0 && str[i]>='0' && str[i]<='9')
{
temp[j++]=str[i];
temp[j]='\0';
i--;
}
//反转
int lent=strlen(temp);
for(int k=0;k<(lent+1)/2;k++)
{
int Temp=temp[k];
temp[k]=temp[lent-1-k];
temp[lent-1-k]=Temp;
}
int a=atoi(temp);
int pos=++i;
i=npos+1;
j=0;
while(i<str.length() && str[i]>='0' && str[i]<='9')
{
temp[j++]=str[i];
temp[j]='\0';
i++;
}
int b=atoi(temp);
if(str[npos]=='+')
result=a+b;
else
result=a-b;
char r[5];
itoa(result,r,10);
string re=r;
str.replace(pos,i-pos,re);
npos1=str.find("+");
npos2=str.find("-");
if(npos1>0 || npos2>0)
jj(str);
}
void fun(string &str)
{
cq(str);
jj(str);
}
void main()
{
string str="8+7*2-9/3";
fun(str);
cout<<str<<endl;
while(cin>>str)
{
fun(str);
cout<<str<<endl;
}
//加减运算
}