C++ 四则运算

题目大意:有字符串表示的一个四则运算表达式,要求计算出该表达式的正确数值。四则运算即:加减乘除"+-*/",另外该表达式中的数字只能是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;
	}
//加减运算

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值