C中的简单浮点计算导致-nan作为值返回

问题描述 投票:0回答:1

我正在编写一个简单的程序来计算文本的可读性,并且在计算平均值时,我得到一个奇怪的结果:“-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;
}

c cs50 readability
1个回答
0
投票

您忘记分配变量。

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

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

© www.soinside.com 2019 - 2024. All rights reserved.