软件工程第一次作业

一、题目:

      阿超有个儿子上小学二年级,老师每天让家长给孩子出30道加减法题,虽然不多,但是每天都做也算是个负担,阿超作为一个老牌程序员当然想用计算机来解决这个小问题,目前对于这个问题对于任何语言都不是问题,比如:

      C/C++、C#、Java、Python、VB、JavaScript、Perl……

    具体要求如下:

  • 能自动生成小学四则运算题目(注意是给小学生用的,要是结果出现负数的话他们会迷茫的!)
  • 除了整数外,还要支持真分数的四则运算

    请大家用任何一种自己擅长的语言来编写这段程序,并把程序的介绍和自己编写的过程写一个博客

二、分析:

      这道题要求的是出题,所以我想到应该用随机数生成来做这道题。在选择编程语言是我选择了C++来实现这个问题。当然除了生成题目,为了方便检查我还直接设置了四则运算,直接生成结果方便阿超检查孩子作业。题目还要求进行真分数运算,为了方便,我将真分数和整数运算分成了两个函数,当输入1时,系统随机生成的为整数,进行整数运算,当输入为其他数时,则生成的是真分数运算。

三、代码:

#include<iostream.h>
#include<stdlib.h>
#include<conio.h>

void DealFenshu(int m, int a[][2])
{
for(int p=0;p<m;p++)
{
int i=(int)rand()%10;
int j=(int)rand()%10;
while(j==0||i>=j)
{
i=(int)rand()%10;
j=(int)rand()%10;
}
int x=(int)rand()%10;
int y=(int)rand()%10;
while(y==0||x>=y)
{
x=(int)rand()%10;
y=(int)rand()%10;
}
int k=(int)rand()%100/25;
switch(k)
{
case 0:
cout<<"("<<i<<"/"<<j<<")"<<"+"<<"("<<x<<"/"<<y<<")"<<"=";
a[p][0]=i*y+x*j;
a[p][1]=j*y;
break;
case 1:
cout<<"("<<i<<"/"<<j<<")"<<"-"<<"("<<x<<"/"<<y<<")"<<"=";
a[p][0]=i*y-x*j;
a[p][1]=j*y;
break;
case 2:
cout<<"("<<i<<"/"<<j<<")"<<"*"<<"("<<x<<"/"<<y<<")"<<"=";
a[p][0]=i*x;
a[p][1]=j*y;
break;
case 3:
a[p][0]=i*y;
a[p][1]=j*x;
cout<<"("<<i<<"/"<<j<<")"<<"/"<<"("<<x<<"/"<<y<<")"<<"=";
}

if(p%5==4)
{
cout<<endl;
}
else
{
cout<<'\t';
}
}

}
void DisplayFenshu(int a[][2],int w,int m)
{
if(w==1)
{
for(int q=0;q<m;q++)
{
if(a[q][0]==0)
cout<<"0"<<'\t';
else
cout<<a[q][0]<<"/"<<a[q][1]<<'\t';
if(q%5==4)
{
cout<<endl;
}
}
}
else
{};
}
void DealInt(int m,int a[])
{

for(int p=0;p<m;p++)
{
int i=(int)rand()%10;
int j=(int)rand()%10;
int k=(int)rand()%100/25;
switch(k)
{
case 0:
cout<<i<<"+"<<j<<"=";
a[p]=i+j;
break;
case 1:
cout<<j<<"-"<<i<<"=";
a[p]=j-i;
break;
case 2:
cout<<i<<"*"<<j<<"=";
a[p]=i*j;
break;
case 3:
try
{
a[p]=i/j;
cout<<i<<"/"<<j<<"=";
}
catch(...)
{
p--;
}

}

if(p%5==4)
{
cout<<endl;
}
else
{
cout<<'\t';
}
}
}
void DisplayInt(int a[],int w,int m)
{
if(w==1)
{
for(int q=0;q<m;q++)
{
cout<<a[q]<<'\t';
if(q%5==4)
{
cout<<endl;
}
}
}
else
{};
}
void main()
{
int p;
do
{
system("cls");
int a[1000],b[1000][2];
int m,n,w;
cout<<"请输入生成的四则运算题个数:";
cin>>m;
cout<<endl;
cout<<"请输入要生成的四则运算种类(输入1为整数,否则为真分数):";
cin>>n;
cout<<endl;
if(n==1)
{
DealInt(m,a);
cout<<endl;
}
else
{
DealFenshu(m,b);
cout<<endl;
}
cout<<"是否输出答案(输入1则输出答案否则不输出答案)"<<endl;
cin>>w;
if(n==1)
{
DisplayInt(a,w,m);
}
else
{
DisplayFenshu(b,w,m);
}
cout<<endl;
cout<<"是否继续生成运算题(输入1则生成否则不生成)"<<endl;
cin>>p;
cout<<endl;
}while(1==p);

}

   

posted on 2016-03-12 17:56  胡逸凡  阅读(214)  评论(2编辑  收藏  举报