【发布时间】:2021-11-17 18:09:17
【问题描述】:
我正在尝试编写一个程序作为练习,从文件中获取一些值,将它们分类为两个变量,名为 studentsPassed 和 studentsFailed,然后打印通过的学生人数和通过的学生人数失败以及模块代码和学生人数。
这是 .txt 文件:
101 20
65 72 23 59 80 75 55 88 92 77 44 57 73 31 48 59 71 48 66 59
101 是模块代码,20 是班级学生人数。下面一行中的 20 个数字是这 20 名学生中每个人的分数(例如学生 1 得 65 分,学生 2 得 72 分等)
这是我的代码:
#include <stdio.h>
FILE *fp;
int main(){
//Open the file and assign its address/disk location to file pointer
fp = fopen("marks.txt", "r");
//Variables
int moduleCode, numStudents;
const int size = 20;
int studentMark;
int studentsPassed;
int studentsFailed;
//Scan in the first line for the module code and the number of students
fscanf(fp, "%d %d", &moduleCode, &numStudents);
//Scan in the student marks and loop through them
for (int i = 0; i < size; i++)
if (fscanf(fp, "%d", &studentMark) < 40){
int studentsFailed = studentsFailed + 1;
}
else if (fscanf(fp, "%d", &studentMark) >= 40){
int studentsPassed = studentsPassed + 1;
}
else{
printf("Error: Number of marks exceeds cap!");
return 0;
}
//Print the results
printf("%d %d\n", moduleCode, numStudents);
printf("Number of students passed: %d\n", studentsPassed);
printf("Number of students failed: %d\n", studentsFailed);
return 0;
}
程序应该做的是读取模块代码和学生人数并将它们打印在第一行(这是成功的),然后程序应该循环遍历 20 个数字中的每一个,并将它们分类为不同的变量如果它们高于或低于 40,这是我正在努力的部分,因为程序执行,但它会为studentsPassed 打印出一个随机的大数,每次我为studentsFailed 打印一个“1”运行它。
我做错了什么?我觉得我错过了与循环遍历每个数字有关的东西,但我不确定如何更正它。
注意:这是我在reading another answer 之前在本网站上最初尝试的(也没有工作)以获得我当前的代码。
//Scan in the student marks and loop through them
fscanf(fp, "%d", &studentMark);
for (int i = 0; i < size; i++)
if (studentMark < 40){
int studentsFailed = studentsFailed + 1;
}
else if (studentMark >= 40){
int studentsPassed = studentsPassed + 1;
}
【问题讨论】:
-
if (fscanf(fp, "%d", &studentMark) < 40)scanf函数系列不是这样工作的。请阅读更多关于what it returns的信息。 -
另外,如果你多次调用
fscanf,它会尝试读取多个值。这意味着您对studentMark的多次调用将跳过每秒的值。