这次老师让我们写一个小学生100以内四则运算的程序,同时还要支持真分数的运算。
对这道题写程序前我的主要思路如下:
1、数字和符号都要是随机生成的,主要用到随机数生成函数srand()和rand()这两个函数来生成随机数。其中运算数是100以内的,符号是4种情况。
2、其中除法运算中除数不能为零要做出判断。对于真分数来说,其分母也不可为零。
3、减法运算中被减数一定要大于减数,因为对于小学生来说不会计算负数。
4、对于真分数有一点特别的,随机生成的分子和分母有可能可以约分。所以我们每次都要先计算分子和分母的最大公约数,再所以最大公约数,得到最简真分数。
5、在主函数中生成两个随机数用做运算,在生成一个随机数用做控制条件。其中有加、减、乘、除和真分数五种情况,分别用switch来调用各个函数。
下面我附上我的源程序:
#include<stdio.h>
#include<iostream>
#include<Windows.h>
#include<time.h>
using namespace std;
int Com(int a, int b)
{
int r;
while (b != 0)
{
r = a%b;
a = b;
b = r;
}
return a;
}
void Add(int a, int b)
{
cout << a << " + " << b << " =" << endl;
return;
}
void Add1(int a, int b, int c, int d)
{
cout << a << "/" << b << " + " << c << "/" << d << " =" << endl;
return;
}
void Sub(int a, int b)
{
if (a < b)
cout << b << " - " << a << " =" << endl;
else
cout << a << " - " << b << " =" << endl;
return;
}
void Sub1(int a, int b, int c, int d)
{
float m, n;
m = (((float)a) / ((float)b));
n = (((float)c) / ((float)d));
if (m < n)
cout << c << "/" << d << " - " << a << "/" << b << " =" << endl;
else
cout << a << "/" << b << " - " << c << "/" << d << " =" << endl;
return;
}
void Mul(int a, int b)
{
cout << a << " * " << b << " =" << endl;
return;
}
void Mul1(int a, int b, int c, int d)
{
cout << a << "/" << b << " * " << c << "/" << d << " =" << endl;
return;
}
void Div(int a, int b)
{
while (b == 0)
{
b = rand() % 100;
}
cout << a << " / " << b << " =" << endl;
return;
}
void Div1(int a, int b, int c, int d)
{
int m;
while (c == 0)
{
c = rand() % 100;
}
m = Com(c, d);
c = c / m;
d = d / m;
cout << a << "/" << b << " / " << c << "/" << d << " =" << endl;
return;
}
void ProFra(int a, int b, int c, int d)
{
int m, n, Sig;
a = rand() % 100;
b = rand() % 100;
c = rand() % 100;
d = rand() % 100;
while (a == b)
{
a = rand() % 100;
}
while (c == d)
{
c = rand() % 100;
}
while (b == 0)
{
b = rand() % 100;
}
while (d == 0)
{
d = rand() % 100;
}
Sig = rand() % 4;
m = Com(a, b);
a = a / m;
b = b / m;
n = Com(c, d);
c = c / n;
d = d / n;
if (a > b)
{
int e;
e = a;
a = b;
b = e;
}
if (c > d)
{
int e;
e = c;
c = d;
d = e;
}
switch (Sig)
{
case 0:Add1(a, b, c, d);
break;
case 1:Sub1(a, b, c, d);
break;
case 2:Mul1(a, b, c, d);
break;
case 3:Div1(a, b, c, d);
break;
}
return;
}
void main()
{
int FirNo,SecNo,Sig,TextNo;
cout << "Plese enter the number of mathematical problems:";
cin >> TextNo;
srand((unsigned)time(NULL));
for (int i = 0; i < TextNo; i++)
{
FirNo = rand() % 100;
SecNo = rand() % 100;
Sig = rand() % 5;
switch (Sig)
{
case 0:Add(FirNo, SecNo);
break;
case 1:Sub(FirNo, SecNo);
break;
case 2:Mul(FirNo, SecNo);
break;
case 3:Div(FirNo, SecNo);
break;
case 4:ProFra(0, 0, 0, 0);
break;
}
}
system("pause");
}
程序还是存在很多不足的地方,代码不够优化,算法不够优化,导致程序效率低。而且小学生也分年级,每年级学的知识不同,出的题也不一样,应该分别考虑出多种情况。对于大多数的人都适用才是一个好的程序。对于这些我也会再继续改进的。