C语言随机10道四则运算
通过计算机随机产生10道四则运算题,两个操作数为1~10之间的随机数,运算类型为随机产生的加、减、乘、整除中的任意一种,如果输入答案正确,则显示“Right!”,否则显示“Not correct!”,不给机会重做,10道题做完后,按每题10分统计总得分,然后打印出总分和做错题数。
编程要求:
1.较好的用户输入输出提示
2.使用子函数实现两个数相加的测试。此函数的输入参数是两个加数,返回值是用户运算的正确与否(用1或者0表示)。在此函数中首先读入用户输入的加法结果,并与正确结果进行比较。
intAddTest(int a, int b) ;
以下是我写的代码,如何改的和题目一样……例如在哪加循环……
#include<stdio.h>
#include<time.h>
#include<stdlib.h>
int a = 0;
int hanshu()
{
int num1,num2,num4,b,result;
int num5=0;
srand(time(0));
num1=rand()%11;
num2=rand()%11;
b=rand()%5;
if(b==1)
{
printf("%d + %d =\n",num1,num2);
num4=num1+num2;
}
if(b==2)
{
printf("%d - %d = \n",num1,num2);
num4=num1-num2;
}
if(b==3)
{
printf("%d * %d = \n",num1,num2);
num4=num1*num2;
}
if(b==4 && num2!=0)
{
printf("%d / %d = \n",num1,num2);
num4=num1/num2;
}
printf("请输入答案");
scanf("%d",&result);
if (result==num4)
{
printf("Right!\n");
num5++;
}
else
{
printf("Not correct\nThe result is:%d\n",num4);
}
printf("%d题目错误",10-num5);
printf("%d分数",num5*10);
return 0;
}
是哪方面一样? 本帖最后由 major_lyu 于 2020-2-16 21:42 编辑
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
int problem_gen_verif(void); //问题生产与答案验证
int AddTest(int a, int b);
int main(void)
{
int i = 10;
srand(time(0));
int correct = 0;
while(i--)
{
correct += problem_gen_verif();
}
printf("%d Errors\n", 10-correct);
printf("Your Score: %d", correct*10);
return 0;
}
int problem_gen_verif(void)
{
int num1;
int num2;
float answer;
float rslt;
unsigned int flag = rand()%4;
switch(flag)
{
case 0: // '+'
num1 = rand()%11;
num2 = rand()%11;
rslt = num1 + num2;
printf("%d + %d = ?\n", num1, num2);
break;
case 1: // '-'
num1 = rand()%11;
num2 = rand()%11;
rslt = num1 - num2;
printf("%d - %d = ?\n", num1, num2);
break;
case 2: // '*'
num1 = rand()%11;
num2 = rand()%11;
rslt = (float)num1 * (float)num2;
printf("%d * %d = ?\n", num1, num2);
break;
case 3: // '/'
num1 = rand()%11;
do
{
num2 = rand()%11;
} while(num2==0);
rslt = (float)num1 / (float)num2;
printf("%d / %d = ?\n", num1, num2);
break;
default:
break;
}
printf("Your Answer: ");
scanf("%f",&answer);
if(fabs(rslt-answer) < 0.01) //精度0.01
{
printf("Right\n");
return 1;
}
else
{
printf("Not correct! The correct answer is %f\n", rslt);
return 0;
}
}
int AddTest(int a, int b)
{
int rslt = a + b;
int answer;
printf("Please input you answer of %d + %d:", a, b);
scanf("%d", &answer);
return (answer==rslt);
}
问题2没太明白。如果是要用 AddTest()判断加法问题是否正确,可以吧case 0:中的代码块改成:
if (AddTest(num1, num2) == 1)
{
printf("Right\n");
return 1;
}
else
{
printf("Not correct\n");
return 0;
} 进来学习下
页:
[1]