给正在上小学的表弟写的数学题目生成器–C语言实现
- 前言:以下代码非常基础,没有任何高深知识,仅供娱乐适合新手观看。大牛慎入!!!
一、思路
简单到没有思路QAQ,
核心步骤是:随机数与switch的综合使用
二、使(折)用(磨)步骤
1.头文件的使用
#include <stdio.h>
#include <time.h> //得到真随机数
#include <stdlib.h>
2.用随机数来实现随机加减乘除效果
(1)随机数的实现
srand((unsigned)time(NULL)); // 提供随机数种子
a = rand() % 4 + 1; // 提供 1~4的随机数
b = rand() % 100; //因为是小学,做100 以内的计算
c = rand() % 100;
i = rand() % 100;
j = rand() % 99 + 1; //该数将要做除数不能为零
(2)用随机数映射不同的数学运算符号
switch(a) //a是随机数1~4
{
case 1: printf("%d + %d = ", b, c);
case 2: printf("%d - %d = ", b, c);
case 3: printf("%d x %d = ", b, c);
case 4: printf("%.0lf ÷%.0lf = ", i, j);
}
3.填写答案
完成了上一步就可以用scanf()将答案输入并判断对错。
不过要注意一点case 4 中的除法题,有可能能结果是无理数,要进行答案的估算
case 4: printf("%.0lf ÷%.0lf = ", i, j);
g = i / j; //四舍五入取两位小数
g = g * 100;
g = g + 0.5;
g = (int)g;
g = g / 100;
printf("请输入答案(结果保留小数点后两位):");
scanf("%lf", &e);
三、效果图
当然你也可以个判断对错的中文字上色
添加一个库函数
#include <windows.h>
在前面加上颜色的函数
void color(short x)
{
if(x>=0 && x<=15)
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), x);
else
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 7);
}
调色
if(e == b + c)
{
color(2); //染绿
printf("\n\t答案正确!\n\n");
color(15); //染成原来的颜色
}
else
{
color(4); //染红
printf("\n\t答案错误!正确答案为:%d\n\n", b + c);
color(15);
}
看效果
四、全部的代码
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
#include <windows.h>
void color(short x)
{
if(x>=0 && x<=15)
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), x);
else
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 7);
}
int main()
{
int a, b, c, d, h = 0;
double e, f, g, i, j;
printf("小学数学题生成器(两位数四则运算)\n\n");
while(1) //无线循环做题
{
srand((unsigned)time(NULL)); // 提供随机数种子
a = rand() % 4 + 1; // 提供 1~4的随机数
b = rand() % 100; //因为是小学,做100 以内的计算
c = rand() % 100;
i = rand() % 100;
j = rand() % 99 + 1; //该数将要做除数不能为零
switch(a)
{
case 1: printf("%d + %d = ", b, c);
scanf("%lf", &e);
if(e == b + c)
{
color(2); //染绿
printf("\n\t答案正确!\n\n");
color(15); //染成原来的颜色
}
else
{
color(4); //染红
printf("\n\t答案错误!正确答案为:%d\n\n", b + c);
color(15);
}
break;
case 2: printf("%d - %d = ", b, c);
scanf("%lf", &e);
if(e == b - c)
{
color(2);
printf("\n\t答案正确!\n\n");
color(15);
}
else
{
color(4);
printf("\n\t答案错误!正确答案为:%d\n\n", b - c);
color(15);
}
break;
case 3: printf("%d x %d = ", b, c);
scanf("%lf", &e);
if(e == b * c)
{
color(2);
printf("\n\t答案正确!\n\n");
color(15);
}
else
{
color(4);
printf("\n\t答案错误!正确答案为:%d\n\n", b * c);
color(15);
}
break;
case 4: printf("%.0lf ÷%.0lf = ", i, j);
g = i / j;
g = g * 100;
g = g + 0.5;
g = (int)g;
g = g / 100;
scanf("%lf", &e);
if(e == g)
{
color(2);
printf("\n\t答案正确!\n\n");
color(15);
}
else
{
color(4);
printf("\n\t答案错误!正确答案为:%0.2lf\n\n", g);
color(15);
}
break;
}
}
return 0;
}