这次老师布置的作业为小学生四则运算,同时还要求掺有真分数的运算。
下面我附上我的源程序:
#include<stdio.h>
#include<stdlib.h>
#include<Windows.h>
#include<time.h>
int main()
{
int i, a, b, d, e, g, h, m, n, o, p;
char c;
srand((unsigned)time(NULL));
printf("*****欢迎进入四则运算*****
");
printf("请输入您的选择:1.整数运算 2.真分数运算
");
scanf("%d", &e);
if (e==1)
{
for (i = 1; i < 31; i++)
{
a = rand() % 100;
b = rand() % 100;
d = rand() % 4;
if (d == 0)
{
c = '+';
printf("%d. %d%c%d=
", i, a, c, b);
}
if (d == 1)
{
c = '-';
if (a > b)
printf("%d. %d%c%d=
", i, a, c, b);
else
printf("%d. %d%c%d=
", i, b, c, a);
}
if (d == 2)
{
c = '*';
printf("%d. %d%c%d=
", i, a, c, b);
}
if (d == 3)
{
c = '/';
if (b == 0)
printf("%d. %d%c%d=
", i, b, c, a);
else
printf("%d. %d%c%d=
", i, a, c, b);
}
}
}
if (e==2)
{
for (i = 1; i < 31; i++)
{
g = 2;// rand() % 100;
h = 2;// rand() % 100;
m = rand() % 100;
n = rand() % 100;
d = rand() % 4;
while (g == h)
{
g = rand() % 100;
}
while (m == n)
{
m = rand() % 100;
}
while (h == 0)
{
h = rand() % 100;
}
while (n == 0)
{
n = rand() % 100;
}
while (g == 0)
{
g = rand() % 100;
}
while (m == 0)
{
m = rand() % 100;
}
if (g>h)
{
o = g;
g = h;
h = o;
}
if (m > n)
{
p = m;
m = n;
n = p;
}
if (d == 0)
{
c = '+';
printf("%d. %d/%d%c%d/%d=
", i, g, h, c, m, n);
}
if (d == 1)
{
float p, q;
p = (float)m / (float)n;
q = (float)g / (float)h;
c = '-';
if (q < p)
printf("%d. %d/%d%c%d/%d=
", i, m, n, c, g, h);
else
printf("%d. %d/%d%c%d/%d=
", i, g, h, c, m, n);
}
if (d == 2)
{
c = '*';
printf("%d. %d/%d%c%d/%d=
", i, g, h, c, m, n);
}
if (d == 3)
{
c = '/';
printf("%d. %d/%d%c%d/%d=
", i, g, h, c, m, n);
}
}
}
system("pause");
return 0;
}
之前我也说过自己的编程能力很弱,在老师布置完这个题目后其实我有点害怕,怕完成不了作业。在整个编程中,我先从最简单的入手,一步步得到自己想要的结果,其中也不乏有些奇怪的问题,但最后都解决了,我的思路很简单,在做减法运算时不让减数比被减数大,在做除法时不让除数为零。最大的一个不足之处就是没有在30道题里既有整数运算又有真分数运算,我在短时间内是想不出来解决的方法了,然后就把真分数的运算单独整理出来,保持真分数是一个大于零小于一的数,在做真分数减法时不让减数比被减数大,其中最主要的函数就是获取随机数srand((unsigned)time(NULL))。通过if语句while语句for循环语句来控制加减乘除运算,这就是我整个的思路。整个c程很简单。