【问题标题】:Simple float calculation in C resulting in -nan coming back as a valueC 中的简单浮点计算导致 -nan 作为值返回
【发布时间】: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,因为wordcount0
  • nan 表示不是数字。例如,您可以通过取负数的平方根来得到它。但是在您的情况下,您是通过将 0 除以 0 得到的,这是不确定的,因此不是数字。
  • 非常感谢大家!我没有意识到这就是我在做的事情。

标签: c cs50 readability


【解决方案1】:

您忘记分配变量。

lettercount = count_letters (text);
wordcount = count_words (text);
sentcount = count_sentences (text);
L = avg_letters (lettercount, wordcount);
S = avg_sents (wordcount, sentcount);

由于您从未分配过它们,它们仍然具有您初始化它们时使用的0 值,因此您将0 除以0avg_lettersavg_sents 中。这会产生nan,它代表not a number

【讨论】:

    猜你喜欢
    • 2012-10-08
    • 1970-01-01
    • 2014-01-21
    • 2014-07-22
    • 2012-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多