首页 > 代码库 > 四则运算(第二版)

四则运算(第二版)

功能1. 四则运算

支持出题4个数的四则运算题目

技术分享

#include<stdio.h>#include<stack>#include<stdlib.h>#include<string>#include<math.h>using namespace std;struct Number{	double a;	bool b;//0数字 1字符 };stack<Number>s3;void houzhuibds(char str[100])//后缀表达式 {		stack<char>s1;	stack<Number>s2;	int i=0,j=0;	for(i=0;str[i]!=‘\0‘;i++)	{		if(str[i]>=‘0‘&&str[i]<=‘9‘)		{			Number num;			num.a=0;			num.b=0;			while(str[i]<=‘9‘&&str[i]>=‘0‘)			num.a=(str[i++]-‘0‘)+num.a*10;			s2.push(num);				i--;		}		else		{			if(str[i]==‘)‘)			{				while(s1.top()!=‘(‘)				{					Number num;					num.b=1;					num.a=s1.top();					s2.push(num);					s1.pop();				}				s1.pop();			}			else if(s1.empty()||s1.top()==‘(‘||str[i]==‘(‘)			{				s1.push(str[i]);			}			else			{				if((str[i]==‘*‘||str[i]==‘/‘)&&(s1.top()==‘+‘||s1.top()==‘-‘))				s1.push(str[i]);				else				{					Number num;					num.b=1;					num.a=s1.top();					s2.push(num);					s1.pop();					i--;				}			}					}	}	while(!s1.empty())	{		Number num;		num.b=1;		num.a=s1.top();		s2.push(num);		s1.pop();	}	while(!s2.empty())	{		s3.push(s2.top());		s2.pop();	}    /*	while(!s3.empty())	{		Number num=s3.top();		s3.pop();		if(num.b==0)		printf("%d",num.a);		else		printf("%c",num.a);			}	printf("\n");	*/}double qiuzhi(){	stack<double>s4;	while(!s3.empty())	{		Number c1=s3.top();		s3.pop();		if(c1.b==0)		s4.push(c1.a);		else		{			double c2=s4.top();			s4.pop();			double c3=s4.top();			s4.pop();			double c4;			switch((int)c1.a)			{				case ‘+‘:c4=c3+c2;break;    			case ‘-‘:c4=c3-c2;break;    			case ‘*‘:c4=c3*c2;break;    			case ‘/‘:c4=c3/c2;break;			}			s4.push(c4);		}	}	return s4.top();}void afterfh(char str[100],int t,int n);//+-*/之后 void aftersz(char str[100],int t,int n);int main(){	char str[100];	int s=0;	for(int i=0;i<20;i++)	{		int t=0;		int n=0;		afterfh(str,t,n);		//gets(str);//4个数3个符号 		houzhuibds(str);		double ans=qiuzhi();		for(int i=0;str[i]!=‘\0‘;i++)		printf("%c",str[i]);		printf("=\n?");		double s;		scanf("%lf",&s);		if(abs(s-ans)<0.01)		{			s++;		    printf("答对了,你真是天才\n");	    }		else		printf("再想想吧,答案似乎是%.2lf喔!\n",ans);    }    printf("你一共答对%d道题,共20道题。\n",s);	return 0;}void aftersz(char str[100],int t,int n){	int num=rand()%4;	switch(num)	{		case 0:str[t]=‘+‘;break;		case 1:str[t]=‘-‘;break;		case 2:str[t]=‘*‘;break;		case 3:str[t]=‘/‘;break;	}	afterfh(str,++t,n);}void afterfh(char str[100],int t,int n)//+-*/之后 {	int num=rand()%100;	if(num>=10)	{		int a=num%10;		str[t++]=num/10+‘0‘;		str[t]=a+‘0‘;	}	else	str[t]=‘0‘+num;	n++;	if(n==4)	{		str[++t]=‘\0‘;		return ;		}	t++;	aftersz(str,t,n);}

  

四则运算(第二版)