如何解决为Linux创建C程序时的浮点异常核心已转储
我是C语言的新手,需要一些帮助,当我执行此代码时,输出显示“浮点异常(内核已转储)”,而不是一个数字,我不知道它可能是什么。我真的不知道我的代码有什么问题,因为我是linux和C的入门者。感谢所有帮助。
这是我的功能。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。
出现浮点异常的主要原因是您访问的文件超出了文件的大小。
在函数total
和count
中,您使用相同的指针,因此在完成total
后,文件指针位于文件末尾,而在{ {1}}。
您需要执行count
,以使指针指向起点。
您所有的块语句和函数都以fseek(file,SEEK_SET,0);
结尾,那是错误的。
假设文件的内容只是像这样的数字;
1 2 3 4 5 6
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。