作业1 四则运算

这是第一次在网上写关于程序代码的博客,第一次老师布置的作业是参考 P2-3页内容.写一个能自动生成小学四则运算题目的程序.和同学们比较一下各自程序的功能、实现方法的异同等等。写第一个博客。

 下面就是程序代码的展示:

 1 #include<stdio.h>
 2 #include<time.h>
 3 #include<stdlib.h>
 4 void main()
 5 {
 6 int a,b,c,d;
 7 int total1=0,total2=0;
 8 while(1)
 9 {
10 srand(time(NULL));//srand函数是随机数发生器的初始化函数
11 d=a=rand()%10;
12 //rand()是一个随机函数,d=a=rand()是将这个随机值赋给d和a,%10是在0-10内取值…d=a=rand()%10就是在0-10内取随机值然后赋给d和a
13 b=(rand()%a+a)%10;
14 if(a%4==1&&a<b)
15 c=a,a=b,b=c;
16 if(b==0&&a%4==3)
17 b=rand()%10+1;
18 if(a%4==3&&a%b!=0)
19 {
20 srand(time(0));
21 a=b*(rand()%a);
22 }
23 switch(d%4)
24 {
25 case 0:
26 printf("%d + %d = ",a,b);
27 break;
28 case 1:
29 printf("%d - %d = ",a,b);
30 break;
31 case 2:
32 printf("%d × %d = ",a,b);
33 break;
34 case 3:
35 printf("%d ÷ %d = ",a,b);
36 break;
37 }
38 scanf("%d",&c);
39 switch(d%4)
40 {
41 case 0:
42 if(c==a+b)
43 {
44 printf("正确
");
45 total1++;
46 }
47 else
48 {
49 printf("错误
");
50 total2++;
51 }
52 break;
53 case 1:
54 if(c==a-b)
55 {
56 printf("正确
");
57 total1++;
58 }
59 else
60 {
61 printf("错误
");
62 total2++;
63 }
64 break;
65 case 2:
66 if(c==a*b)
67 {
68 printf("正确
");
69 total1++;
70 }
71 else
72 {
73 printf("错误
");
74 total2++;
75 }
76 break;
77 case 3:
78 if(c==a/b)
79 {
80 printf("正确
");
81 total1++;
82 }
83 else
84 {
85 printf("错误
");
86 total2++;
87 }
88 break;
89 }
90 printf("按任意键继续,Q退出!
");
91 fflush(stdin);
92 if(getchar()=='Q')
93 break;
94 }
95 printf("你答对了%d道题,答错%d道题
",total1,total2);
96 }

 首先,这是二年级的四则运算,所以数字范围应该是在1~10之间,于是我就用到了d=a=rand()%10;这个代码,把数字控制在1~10之间,于是我又想到做出了之后需要确定对错和做对做错多少题,于是代码就可以写成:

1  switch(d%4){case 0:if(c==a+b){printf("正确
");total1++;}else{printf("错误
");total2++;}break;
2 case 1:if(c==a-b){printf("正确
");total1++;}else{printf("错误
");total2++;}break;
3 case 2:if(c==a*b){printf("正确
");total1++;}else{printf("错误
");total2++;}break;
4 case 3:if(c==a/b){printf("正确
");total1++;}else{printf("错误
");total2++;}break;
 
total1是指做对的题数,total2是指做错的题数。
 
接着我还想到一个功能,还可以退出的功能:
1 printf("按任意键继续,Q退出!
");
2 fflush(stdin);
3 if(getchar()=='Q')
4 break;
原文地址:https://www.cnblogs.com/babybluecsj/p/4367301.html