#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
//将学生答题写入文件result.txt,将正确答案写入answer.txt文件
void write()
{
int num1, num2, result, answer; //定义左右操作数与答案
FILE* fresult = fopen("D:\\result.txt", "w+");
FILE* fanswer = fopen("D:\\answer.txt", "w+");
if (fresult == NULL || fanswer == NULL)
{
printf("答题写入失败!\n");
exit(0);
}
printf("请作答题目:\n");
srand((unsigned int)time(NULL));
for (int i = 0; i < 10; i++)
{
num1 = rand() % 50;
num2 = rand() % 50;
printf("%d+%d=", num1, num2);
scanf("%d", &result);
answer = num1 + num2;
//将学生结果写入result.txt文件中
fprintf(fresult, "%d+%d=%d", num1, num2, result);
fputc('\n', fresult);
//将正确答案的结果写入answer.txt文件中
fprintf(fanswer, "%d+%d=%d", num1, num2, answer);
fputc('\n', fanswer);
}
fclose(fresult);
fclose(fanswer);
}
//计算得分
void score()
{
/*
读取result.txt文件与ansnwer.txt文件,
比较最后一列结果与答案是否相等,相等则重量正确,得10分,
*/
int num1=0, num2=0, result=0, answer=0, sum=0;
FILE* fresult = fopen("D:\\result.txt", "r+");
FILE* fanswer = fopen("D:\\answer.txt", "r+");
if (fresult == NULL || fanswer == NULL)
{
printf("文件打开失败!\n");
exit(0);
}
printf("答案核对:\n");
for (int i = 0; i < 10; i++)
{
//读出学生的作答
fscanf(fresult, "%d+%d=%d", &num1, &num2, &result);
//读出正确答案
fscanf(fanswer, "%d+%d=%d", &num1, &num2, &answer);
if (result == answer)
{
printf("%d+%d=%d \t答案正确 +10\n", num1, num2, result);
sum += 10;
}
else
printf("%d+%d=%d \t答案错误 +0\n", num1, num2, result);
}
printf("您本次得分:%d\n", sum);
fclose(fresult);
fclose(fanswer);
}
int main()
{
write();
score();
return 0;
}