为 Linux 创建 C 程序时出现浮点异常(核心已转储)

Floating point exception (core dumped) while creating a C program for Linux

我是 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;
};

在此声明中

int theMean= theSum/theCount;

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

出现浮点数异常的主要原因是您正在访问超出其大小的文件。

在函数 totalcount 中,您使用的是相同的指针,因此当完成 total 时,文件指针位于文件末尾,您使用的是相同的指针在 count 也。

您需要fseek(file,SEEK_SET,0);,使指针指向开头。

而且你们所有的块语句和函数都以 ; 结尾,那是错误的。

我已经更正了整个程序,假设文件的内容只是这样的数字 1 2 3 4 5 6

#include <stdio.h>

#define WORDS 100

int count(FILE *file){
    int count = 0,n; 
    char word[WORDS];
    // you need this to access the elements from start of the file
    // comment below line causes sigfpe, Floating point exception
    fseek(file,SEEK_SET,0);
    printf(" position of fptr in count = %d\n",ftell(file));
    while(fscanf(file,"%s",word)==1 ){ 
        count++;
    }
    return count;
}

int total( FILE *file ){ 
    int numbers, sum = 0;
    int token;
    // This is checked after number is read, will add the last number 2 times 
    //while(token != EOF){ 
    while(1)
    {
        token = fscanf(file,"%d",&numbers);
        printf("N = %d, token = %d\n", numbers, token);
        if(token == EOF )
            break;
        sum += numbers;
    }
    printf(" position of fptr in total  at the end = %d, sum = %d\n",ftell(file), sum);
    return sum;
}

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); 
    //make sure to add a check that `theCount` is not zero
    int theMean = theSum/theCount; 

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

    return 0;
}