【发布时间】:2020-04-07 05:06:27
【问题描述】:
我正在编写一个简单的程序来计算文本的可读性,在计算平均值时,我得到了一个奇怪的结果:“-nan”。这是我的代码底部的两个浮点计算函数返回的结果,当我计算主函数中的索引时,我得到一个负数。这应该是不可能的,因为被划分的数字都不是负数。任何人都知道 -nan 是什么意思或我该如何解决这个问题?
谢谢!
#include <stdio.h>
#include <string.h>
int count_letters (string text);
int count_words (string text);
int count_sentences (string text);
float avg_letters (int lettercount, int wordcount);
float avg_sents (int wordcount, int sentcount);
int main (void)
{
string text = get_string("Text: ");
int lettercount = 0;
int wordcount = 0;
int sentcount = 0;
float S = 0;
float L = 0;
count_letters (text);
count_words (text);
count_sentences (text);
avg_letters (lettercount, wordcount);
avg_sents (wordcount, sentcount);
float index = 0.0588 * L - 0.296 * S - 15.8;
printf("%f\n", index);
}
//Counts letters in entire text
int count_letters (string text)
{
int lettercount = 0;
for (int i=0, n = strlen(text); i<n; i++)
{
if ((text[i] > 64 && text[i] < 91) || (text[i] > 96 && text[i] < 123))
{
lettercount ++;
}
}
printf ("%i\n", lettercount);
return lettercount;
}
//Counts words in text
int count_words (string text)
{
int wordcount = 0;
for (int i=0, n = strlen(text); i<n; i++)
{
if (text[i] == 32)
{
wordcount ++;
}
}
wordcount += 1;
printf ("%i\n", wordcount);
return wordcount;
}
//Counts sentences in text
int count_sentences (string text)
{
int sentcount = 0;
for (int i=0, n = strlen(text); i<n; i++)
{
if ((text[i] == 33) || (text[i] == 63) || (text[i] == 46))
{
sentcount ++;
}
}
printf ("%i\n", sentcount);
return sentcount;
}
//Averages letters per 100 words
float avg_letters (int lettercount, int wordcount)
{
float L = ((float) lettercount / wordcount) * 100;
printf("%f\n", L);
return L;
}
//Averages sentences per 100 words
float avg_sents (int wordcount, int sentcount)
{
float S = ((float) sentcount / wordcount) * 100;
printf("%f\n", S);
return S;
}
【问题讨论】:
-
您永远不会将函数的返回值分配给变量。
-
lettercount / wordcount除以0,因为wordcount是0。 -
nan表示不是数字。例如,您可以通过取负数的平方根来得到它。但是在您的情况下,您是通过将 0 除以 0 得到的,这是不确定的,因此不是数字。 -
非常感谢大家!我没有意识到这就是我在做的事情。
标签: c cs50 readability