gpt4 book ai didi

c - 从文件中的列中读取值

转载 作者:太空宇宙 更新时间:2023-11-04 01:02:24 25 4
gpt4 key购买 nike

我正在尝试从文件中的特定列(忽略第一个数字)读取值,然后找到该列的平均值。到目前为止,我有这段代码可用于读取和查找行的平均值,但不适用于该列。

#include <stdio.h>
#include <stdlib.h>

int main(){

FILE *fp;
int id;
float mark1;
float mark2;
float mark3;
float mark4;
int number;
float average;

fp= fopen("grades.txt", "r");

if(fp == NULL){
printf("File cannot be opened");
exit(-1);
}

while(fscanf(fp, "%d %f %f %f %f", &number, &mark1, &mark2, &mark3, &mark4 ) != EOF){
//code to calculate average and print output
//Below is the code I used to find the average of the line (not what I want to do)
average = (mark1 + mark2 + mark3+ mark4)/4;
printf("Average for %d : %.2f\n", number, average);

}

fclose(fp);
}

所以在文件中一共有5列,第一列是刚好是整数的ID和整数值(int number),其他的数字都是 float 。

文件内容:

12345 60 30 63.2 95
54321 54.2 49 40.5 80
15243 99.5 100 90 98

最佳答案

您可以保留一个变量 sum 来添加特定列的所有值,然后使用它来获取平均值,例如

int sum=0, n=0;

while(fscanf(fp, "%d %f %f %f %f", &number, &mark1, &mark2, &mark3, &mark4 ) != EOF){
//code to calculate average and print output
//Below is the code I used to find the average of the line (not what I want to do)
average = (mark1 + mark2 + mark3+ mark4)/4;
printf("Average for %d : %.2f\n", number, average);

sum += mark2 //this can be any mark depending on your requirement
n++; //this is to keep track of the number of lines

}

printf("the average of column 2 is %d", (sum/n) );

关于c - 从文件中的列中读取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33384806/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com