gpt4 book ai didi

c++ - 获取浮点异常(核心转储)。我不知道如何解决

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

关键函数是报错。至少那是 gdb 所说的。提前致谢。

#include <stdio.h>
#include <stdlib.h>
#include <iostream> // for cin and cout in C++
#include <cassert> // for assert
#include <strings.h>
#include <string.h>
#include<time.h>
using namespace std;

int lcombinations=0;
int distinct=0;

线性哈希函数。

void linear(char *tword, int key, int n, char **lcArray)
{
int c;
while(c==0)
{
if(key==n)
{
key=0;
}
if(strlen(lcArray[key])==0)
{
lcArray[key]=tword;
c=1;
}
else
{
key++;
lcombinations++;
}
}
}

为散列函数生成 key

void key(char *tword, int l, int n, char **lcArray)
{
int total=0;
int k;
for(int i=0; i<l; i++)
{
total= total+tword[i];
}
total=n%total;
k=rand()%25+66;
total=total*k;
linear(tword, total, n, lcArray);
}

int counter=0;

在测试中找到所有不同的词。

void distinct_words(char *tword, char **distinct, int l, int n, char **lcArray)
{
int j;
int k=0;
if(counter==0)
{
counter++;
distinct[0]=tword;
key(tword,l,n,lcArray);
}
else
{
for(j=0; j<counter; j++)
{
if(strcmp(distinct[j],tword)!=0)
{
k++;
}
}
if(k==counter)
{
distinct[counter]=tword;
counter++;
key(tword,l, n, lcArray);
}
}

接收文本并将其分解成单词

int main()
{
srand(time(NULL));
FILE *inFile;
char word[81];
char *tword;
inFile = fopen("will.txt", "r"); // Open for reading, hence the "r"
assert( inFile); // make sure file open was OK
int i=0;
int n=65437;
int j,k;
char **distinct= (char **)malloc(sizeof(char **)*n);
char **lcArray= (char **) malloc(sizeof(char*)*n);
for(int p=0; p<n; p++)
{
lcArray[p]= (char *) malloc(sizeof(char)*81);
}
while(fscanf(inFile, "%s",word) != EOF)
{
i++;
k= strlen(word);
tword= (char *)malloc(sizeof(char)*k);
int l=0;
for(j=0; j<k; j++)
{
if(isalnum(word[j]))
{
word[j]=toupper(word[j]);
tword[l]=word[j];
l++;
}
}
printf("%s ", tword);
distinct_words(tword, distinct, l, n, lcArray);
}

}

最佳答案

我怀疑你的浮点异常是由这一行产生的:

total=n%total;

... 具体来说,如果总计为零,则可能会在许多系统上导致浮点异常。

您可以通过防止模值为零的可能性来避免异常:

if (total != 0)
{
total=n%total;
}
else
{
printf("Hey, modulo by zero is undefined! (It's similar to divide-by-zero!)\n");
total = 0; // or something
}

顺便说一句,如果您想在编程时保持理智,您需要学习的一件关键事情是如何准确追踪代码中发生崩溃的位置。您可以使用调试器执行此操作(通过单步执行代码和/或设置断点),或者您可以通过在整个代码中散布临时 printf()(或类似的)来推断崩溃发生的位置,以便您可以看到崩溃前打印的内容,并使用它来缩小问题位置。两种技术都行得通,当仅仅盯着代码无法给您答案时,通常需要其中一种技术。

关于c++ - 获取浮点异常(核心转储)。我不知道如何解决,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29616777/

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