我写了一个用于计算文本中特定单词频率的函数。该程序每次都返回零。我该如何改进它?计算文本中某个单词的频率数
while (fgets(sentence, sizeof sentence, cfPtr))
{
for(j=0;j<total4;j++)
{
frequency[j] = comparision(sentence,&w);
all_frequency+=frequency[j];
}}
.
.
.
int comparision(const char sentence[ ],char *w)
{
int length=0,count=0,l=0,i;
length= strlen(sentence);
l= strlen(w);
while(sentence[i]!= '\n')
if(strncmp(sentence,w,l))
count++;
i++;
return count;
}
我很惊讶你的程序甚至回报。你使用了一个未初始化的'i',它在'while(sentence [i]!='\ n')中永远不会增加',因为由于缺少大括号,你的'i ++;'超出了循环范围。 –
目前还不清楚w是什么,频率数组是如何初始化的,以及total4的含义。这不是一个很好的证明问题。 – catfood
w是取自用户的单词。总数4是段落数量。 – user2500540