给学生出四则运算考试题,通过计算机随机产生10道四则运算题,两个操作数位1~10之间的随机数,运算类型为随机产生的加,减,乘,除中的任意一种,输入正确答案,则显示“Rigth!”,否则显示“Not correct!",10道做完,按每题10分统计,然后打印总分和做错题数。程序代码:
#include<stdio.h>
#include<time.h>
#include<math.h>
#include<stdlib.h>
int add(void); //加法函数
int sub(void); //减法
int mul(void); //乘法
int div(void); //除法
int main()
{
int (*pf[4])(void); //定义一个长度为4的函数指针数组
int count=0,grade=0,wrong_answer=0;
double result; //定义学生输入的结果
srand((unsigned)time(0)); //初始化随机种子
pf[0]=add;
pf[1]=sub;
pf[2]=mul;
pf[3]=div;
do
{
if((pf[rand()%4])()==1) //随机调用四则运算函数,学生答对函数返回1,否则0
grade+=10;
else
wrong_answer++; //统计做错题目的数量
count++;
}while(count<10);
printf("grade=%d,the number of wrong answer is %d\n",grade,wrong_answer);
return 0;
}
int add(void)
{
double result;
double x,y;
srand((unsigned)time(0));
x=(rand()%100)*0.1f; //产生一个0到10的实数
y=(rand()%100)*0.1f;
printf("%.1f+%.1f=",x,y);
scanf("%lf",&result);
if(fabs(x+y-result)<0.01) //比较两个数是否相等
{
printf("Right!\n");
return 1;
}
else
{ printf("Not correct!\n");
return 0;
}
}
int sub(void)
{ double result,x,y;
srand((unsigned)time(0));
x=(rand()%100)*0.1f;
y=(rand()%100)*0.1f;
printf("%.1f-%.1f=",x,y);
scanf("%lf",&result);
if(fabs(x-y-result)<0.01)
{
printf("Right!\n");
return 1;
}
else
{
printf("Not correct!\n");
return 0;
}
}
int mul(void)
{ double result,x,y;
srand((unsigned)time(0));
x=(rand()%100)*0.1f;
y=(rand()%100)*0.1f;
printf("%.1f*%.1f=",x,y);
scanf("%lf",&result);
if(fabs(x*y-result)<0.01)
{
printf("Right!\n");
return 1;
}
else
{
printf("Not correct!\n");
return 0;
}
}
int div(void)
{ double result;
double x,y;
srand((unsigned)time(0));
x=(rand()%100)*0.1f;
y=(rand()%100)*0.1f;
printf("%.1f/%.1f=",x,y);
scanf("%lf",&result);
if(fabs(x/y-result)<0.01)
{
printf("Right!\n");
return 1;
}
else
{
printf("Not correct!\n");
return 0;
}
}
[
本帖最后由 ZJQLOVELYY 于 2012-1-27 16:09 编辑 ]