代码1—四则运算
首先,这是一个针对小学生的程序。老师提醒我们注意了不能出现负数。由此,我也总结了几个需要注意的问题:
1.需要通过获取随机数的方法,获得数据。四则运算符号也随机
2.除法分母不能得0,真分数运算同样,且真分数除法分母也不为0。
3.我是通过( / )的方式表示真分数,通过获取两个随机数组成,在真分数减法的时候,判断是否为负,通过了最小公倍数通分,和最大公约数判定分子来判断真分数大小的
4.尽可能实现模块化,方便拓展
介绍:
1.Simple()函数简单四则运算
2.pro_fraction()函数真分数四则运算
本次设计,从构思到实现,基本上一个晚上的时间。首先是构思,除了老师提示我们的关于负数的问题,我参考了网上小学数学题,结合自身数学知识,发现了如上几个问题,从源头上制止BUG的产生。接下来,我简单绘制了这个程序的大概程序流程图,了解了大概的框架,最后实现了这个程序并进行了简单的测试,确认程序正确后开始写这篇博客了。
期待下次的练习。
代码如下:
#include<stdio.h>
#include<stdlib.h>
#include<windows.h>
#include<time.h>
void Simple()
{
int i, a, b, c, t, m;
for (m = 0; m < 30; m++)
{
switch (rand() % 4)
{
case 0:
{
printf("%d+", rand() % 100);
printf("%d=\n", rand() % 100);
break;
}
case 1:
{
a = rand() % 100;
b = rand() % 100;
if (a < b)
{
t = a;
a = b;
b = t;
}
printf("%d-", a);
printf("%d=\n", b);
break;
}
case 2:
{
printf("%d*", rand() % 100);
printf("%d=\n", rand() % 100);
break;
}
case 3:
{
printf("%d/", rand() % 100);
c = rand() % 100;
while (1)
{
if (c != 0)
{
printf("%d=\n", c);
break;
}
else
c = rand() % 100;
}
break;
}
}
}
}
int maxnum(int n,int m)
{
int temp,r;
if (n<m)
{
temp = n;
n = m;
m = temp;
}
while (m != 0)
{
r = n%m;
n = m;
m = r;
}
return n;
}
int mininum(int a, int b)
{
int p,n;
p = a*b;
n=maxnum(a, b);
return p / n;
}
int judge(int a)
{
while (1)
{
if (a != 0)
{
break;
}
else
a = rand() % 100;
}
return a;
}
int judge_equal(int a, int b)
{
while (1)
{
if (a >= b)
{
a = rand() % 100;
}
else
{
break;
}
}
return a;
}
void pro_fraction()
{
int i, j, a, b, c, d, t, e, f, g;
for (j = 0; j < 30; j++)
{
a = (rand() % 100);
b = (rand() % 100);
b = judge(b);
a = judge_equal(a, b);
c = (rand() % 100);
d = (rand() % 100);
d = judge(d);
c = judge_equal(c, d);
switch (rand() % 4)
{
case 0:
{
printf("(%d/%d)+", a / maxnum(a, b), b / maxnum(a, b));
printf("(%d/%d)=\n", c / maxnum(c, d), d / maxnum(c, d));
break;
}
case 1:
{
a = a / maxnum(a, b);
b = b / maxnum(a, b);
c = c / maxnum(c, d);
d = d / maxnum(c, d);
e = mininum(b, d);
f = e / b*a;
g = e / d*c;
while (1)
{
if (f < g)
{
printf("(%d/%d)-", c / maxnum(c, d), d / maxnum(c, d));
printf("(%d/%d)=\n", a / maxnum(a, b), b / maxnum(a, b));
break;
}
else
{
printf("(%d/%d)-", a / maxnum(a, b), b / maxnum(a, b));
printf("(%d/%d)=\n", c / maxnum(c, d), d / maxnum(c, d));
break;
}
}
break;
}
case 2:
{
printf("(%d/%d)*", a / maxnum(a, b), b / maxnum(a, b));
printf("(%d/%d)=\n", c / maxnum(c, d), d / maxnum(c, d));
break;
}
case 3:
{
c = judge(c);
printf("(%d/%d)/", a / maxnum(a, b), b / maxnum(a, b));
printf("(%d/%d)=\n", c / maxnum(c, d), d / maxnum(c, d));
break;
}
}
}
}
void menu()
{
int oper;
printf("请选择操作:\n");
printf("1.简单四则运算\n");
printf("2.真分数四则运算\n");
printf("3.退出\n");
scanf("%d", &oper);
srand((unsigned)time(NULL));
switch (oper)
{
case 1:
Simple();
break;
case 2:
pro_fraction();
break;
case 3:
exit(-1);
}
}
int main()
{
int i;
while(1)
menu();
system("pause");
return 0;
}