C语言binary +操作数报错及文件读取体重求和失效问题
问题原因
你遇到的编译报错和运行异常来自两个独立的代码问题:
- 编译错误根源:
sum_weight_animals函数中定义了float weight[20]数组类型,数组名本质是float*指针,直接和float类型的sum_weight做加法运算时类型不匹配,触发invalid operands to binary + (have ‘float’ and ‘float *’)报错。你之前的调整没有修正这个逻辑错误,只是勉强通过了编译。 - 运行时读不到体重数据的根源:C语言的文件流内部维护了一个读写位置指针,调用
count_animals遍历完整个文件后,位置指针已经停在文件末尾(EOF位置),此时直接调用sum_weight_animals执行fscanf会直接读到结束标志,读不到任何有效数据,返回值为0,触发空文件警告。
修复方案
- 调用
count_animals完成计数后,使用rewind(fileptr)将文件位置指针重置到文件开头,保证后续读取体重的操作可以从头遍历文件内容。 - 修正
sum_weight_animals中的变量定义:不需要用数组存储单个体重值,将float weight[20]改为单个float weight变量,fscanf读取时传入&weight取变量地址,累加时直接对weight做加法,彻底解决类型不匹配问题。 - 可选优化:动物计数是整数值,将
count_animals的返回值从float改为int类型,避免浮点数存储整数的精度问题。
修正后完整代码
funciones.c
#include "header.h" int count_animals(FILE *file){ int total_animals = 0; char word[20]; while (fscanf(file, "%s", word) == 1){ total_animals++; } return total_animals; } float sum_weight_animals(FILE *file){ float sum_weight = 0; float weight; while (fscanf(file, "%f", &weight) == 1){ sum_weight += weight; } return sum_weight; }
header.h
#include <stdio.h> #define MAXWORD 80 int count_animals(FILE *file); float sum_weight_animals(FILE *file);
main.c
#include "header.h" int main(){ char file_name[MAXWORD]; FILE *fileptr; printf("Please, enter a file name: "); scanf("%s", file_name); printf("Reading file %s...\n", file_name); fileptr = fopen(file_name, "r"); if(fileptr == NULL){ fprintf(stderr, "ERROR: The file '%s' doesn't exists\n", file_name); return 1; } int total_animals = count_animals(fileptr); if (total_animals > 0){ printf("There're %d animals.\n", total_animals); } else{ fprintf(stderr, "WARNING: File not found or it's empty\n"); fclose(fileptr); return 1; } // 重置文件指针到开头 rewind(fileptr); float total_sum = sum_weight_animals(fileptr); if (total_sum > 0){ printf("The sum of all animal's weight is %.2f [kg].\n", total_sum); printf("The average weight is %.2f [kg].\n", total_sum / total_animals); } else{ fprintf(stderr,"WARNING: File not found or it's empty\n"); } fclose(fileptr); return 0; }
内容的提问来源于stack exchange,提问作者JOSE MINUCHE ESPINOZA
相关产品推荐
相关产品推荐

