生成四则运算题

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/imotolove/article/details/82811944

这是一次随堂测验,要求生成一些小学数学题目,为了降低难度,并没有加入括号

#include<iostream>
#include<cstdlib>
#include<time.h>
using namespace std;
char s[4]={'+','-','x','/'};//符号 
void make(int n)//操作数个数 
{
	int ans=0,cf=1,f=0,x,y,z;
	for(int i=1;i<n;++i)
	{
	  x=rand()%100+1,y=rand()%4;
	  if(s[y]=='x'||s[y]=='/')
	  {
	  	if(f==0)
	  	{
	  		cf*=x; 
		}
		else if(f==1)
		{
			cf*=-x;
		}
		else if(f==2)
		{
			cf*=x;
		}
		else
		{
			cf/=x;
		}
	  }
	  else 
	  {
	  	if(f==0)
	  	{
	  		ans+=x;
		}
		else if(f==1)
		{
			ans-=x;
		}
		else if(f==2)
		{
			cf*=x;
			ans+=cf;
			cf=1;
		}
		else
		{
		   cf/=x;
		   ans+=cf;
		   cf=1;	
		}
	  }
	  cout<<x<<s[y];
	  f=y; //上一次符号 
	}
	z=rand()%100+1;
		if(f==0)
	  	{
	  		ans+=z;
		}
		else if(f==1)
		{
			ans-=z;
		}
		else if(f==2)
		{
			cf*=z;
			ans+=cf;
			cf=1;
		}
		else
		{
		   cf/=z;
		   ans+=cf;
		   cf=1;	
		}
	cout<<z<<"= "<<ans<<endl;
	
}
int main()
{
	for(int i=1;i<=30;++i)
	make(rand()%7+2); 
	return 0;
} 

猜你喜欢

转载自blog.csdn.net/imotolove/article/details/82811944