用C 一个练习算术的小程序。编写加、减、乘、除4个自定义函数:jia(),jian(),cheng(),chu(),在主函数中调用这4个函数去完成以下功能:(1)随机生成5道四则运算题,题目的类型由加、减、乘、除中任意类型混合出题(即5道题目中有各种类型的题目),每道题目的两个整数是20以内的随机数,题目显示在屏幕上,由用户输入答案(如下图所示)。(2)程序判断用户输入的答案是否正确,统计答题的正确率,并将每次的答题正确率保存到result.txt文本文件中。运行结束时,询问是否继续练习,如果回答"Y"则继续进行练习,如果回答"N"则退出练习。
时间: 2024-02-15 21:01:35 浏览: 135
好的,以下是您要求的 C 代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int jia(int a, int b) { return a + b; }
int jian(int a, int b) { return a - b; }
int cheng(int a, int b) { return a * b; }
int chu(int a, int b) { return a / b; }
int main() {
char choice;
int correct_count = 0;
float accuracy = 0.0;
srand(time(NULL));
do {
int i;
for (i = 0; i < 5; i++) {
int a = rand() % 20 + 1;
int b = rand() % 20 + 1;
int op = rand() % 4;
int result, answer;
printf("(%d) ", i + 1);
switch (op) {
case 0:
printf("%d + %d = ", a, b);
result = jia(a, b);
break;
case 1:
printf("%d - %d = ", a, b);
result = jian(a, b);
break;
case 2:
printf("%d * %d = ", a, b);
result = cheng(a, b);
break;
case 3:
printf("%d / %d = ", a, b);
result = chu(a, b);
break;
}
scanf("%d", &answer);
if (answer == result) {
printf("Correct!\n");
correct_count++;
} else {
printf("Wrong! The answer is %d.\n", result);
}
}
accuracy = (float)correct_count / 5 * 100;
printf("Your accuracy is %.2f%%.\n", accuracy);
FILE *fp = fopen("result.txt", "a");
fprintf(fp, "%.2f%%\n", accuracy);
fclose(fp);
printf("Do you want to continue? (Y/N) ");
scanf(" %c", &choice);
correct_count = 0;
} while (choice == 'Y' || choice == 'y');
printf("Thank you for using the program!\n");
return 0;
}
```
这个程序中使用了 `srand()` 函数和 `rand()` 函数来生成随机数,`time(NULL)` 函数用来获取当前时间戳作为随机数种子。程序使用了 `do-while` 循环来进行多次练习,每次练习都会生成 5 道随机的四则运算题,用户需要输入答案,程序会判断答案的正确性并统计正确率,然后将正确率保存到 `result.txt` 文件中。最后询问用户是否继续练习,如果回答是则继续,否则退出程序。
阅读全文