用C语言知识,随机生成20道20以内的加减乘除,输入答案自动判断正误,得分,正确率的简单编程
时间: 2024-12-18 22:17:21 浏览: 12
在C语言中,你可以使用`<stdio.h>`库来实现这个简单的数学测试程序。这里是一个基础的示例,用于生成题目、获取用户输入并进行基本的错误检查:
```c
#include <stdio.h>
#include <stdlib.h> // 包含rand() 和 srand()
// 随机生成数的函数
int random_number(int min, int max) {
return min + rand() % (max - min + 1);
}
int main() {
int correct_answers = 0;
int total_questions = 20;
int score = 0;
float rate;
// 初始化随机数种子
srand(time(NULL));
for (int i = 0; i < total_questions; i++) {
int num1, num2, operation;
int answer;
// 随机选择操作符
switch (rand() % 4) {
case 0: // 加法
num1 = random_number(0, 20);
num2 = random_number(0, 20);
printf("题目 %d: %d + %d = ", i+1, num1, num2);
scanf("%d", &answer);
break;
case 1: // 减法
num1 = random_number(0, 20);
num2 = random_number(num1, 20); // 保证结果非负
printf("题目 %d: %d - %d = ", i+1, num1, num2);
scanf("%d", &answer);
break;
case 2: // 乘法
num1 = random_number(1, 20);
num2 = random_number(1, 20);
printf("题目 %d: %d * %d = ", i+1, num1, num2);
scanf("%d", &answer);
break;
case 3: // 除法
num1 = random_number(1, 20);
if (num1 == 0) { // 避免除数为零
continue; // 跳过当前循环
}
num2 = random_number(1, num1);
printf("题目 %d: %d / %d = ", i+1, num1, num2);
scanf("%d", &answer);
break;
}
// 判断答案是否正确
if (answer == num1 + num2 || answer == num1 - num2 || answer == num1 * num2 || (num1 > 0 && answer == num1 / num2)) {
printf("正确!\n");
correct_answers++;
} else {
printf("错误。\n");
}
}
score = (correct_answers / total_questions) * 100;
rate = (float)correct_answers / total_questions;
printf("\n总分: %d\n正确率: %.2f%%\n", score, rate);
return 0;
}
```
阅读全文