首页 > 解决方案 > 为 Linux 创建 C 程序时出现浮点异常(核心转储)

问题描述

我是 C 新手,需要一些帮助,当我执行此代码时,输​​出显示“浮点异常(核心转储)”而不是一个我不知道它可能是什么的数字。我真的不知道我的代码有什么问题,因为我是 Linux 和 C 的初学者。感谢您的每一个帮助。

这是我的functions.c:

#include "header.h"

int count(FILE *file){
    int count=0,n; 
    char word[WORDS];
    while(fscanf(file,"%s",word)==1 ){ 
        count++;
    };
    return count;
};

int total(FILE *file){ 
    int numbers, sum=0;
    int token;
    while(token!=EOF){ 
        token=fscanf(file,"%d",&numbers);
        sum+=numbers;
    };
    return sum;
};

这是我的main.c:

#include "header.h"

int main(){
    char word[WORDS];
    char theFile[WORDS]; 
    FILE *fileptr;
    printf("Enter the file name: ");
    scanf("%s",theFile); 

    printf("Reading file %s...\n", theFile);
    fileptr=fopen(theFile,"r");

    if(fileptr==NULL){ 
        fprintf(stderr,"ERROR: The file '%s' does not exist\n", theFile);
        return 1;
    };

    int theSum=total(fileptr); 
    int theCount=count(fileptr); 
    int theMean= theSum/theCount; 

    printf("Average weight: %d \n", theMean);

    return 0;
};

标签: cexceptioncoredump

解决方案


在这份声明中

int theMean= theSum/theCount;

theCount为 0 时,您除以零,这是未定义的行为,可能导致 FPE。


推荐阅读