C++四則演算

2591 ワード

文字列で表される4つの演算式で、その式の正しい数値を計算する必要があります.4つの演算は、プラスマイナス乗除「+-*/」であり、また、この式の数字は1ビット(数値範囲0~9)しかありません.また,整除できない場合は下向きに整頓するとeg:8/3の値が2となる.
「8+7*2-9/3」という文字列があれば、その値は19と計算されます.
主なポイント:
1.数字の文字形式を数字形式に変換する方法; 
2.数値の数値形式を数値の文字列形式に変換する方法.
#include 
#include 
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= npos10)  //    
	{
		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='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= npos10)  //    
	{
		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='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)
	{
	fun(str);
	cout<