【问题标题】:readability returning negative value返回负值的可读性
【发布时间】:2020-11-20 17:30:11
【问题描述】:

我已经使用 C 编写了 cs50 可读性的代码。无论我使用什么句子进行测试,我都会收到一个负值。这显然是我的数学问题,但是使用了调试器,我可以看到在实施 Coleman-Liau 索引之前一切似乎都是正确的。我不确定出了什么问题。我在下面添加了代码。

#include <stdio.h>
#include <cs50.h>
#include <string.h> //getstring
#include <math.h>
#include <ctype.h>


int main (void) 
    {
        string text = get_string ("Text:") ; //get input from user
        int letter = 0, word = 1, sentance = 0; 
        
        for (int i = 0, n = strlen(text); i < n; i++) 
      
        if (isalpha(text[i]))      //identify how many characters are alphabetical
        {
            letter++;
        }
        
        for (int i = 0, n = strlen(text); i < n; i++) 
        if (isspace(text[i]))     //identify how many spces there are 
        {
            word++;
        }
        
        for (int i = 0, n = strlen(text); i < n; i++)
        if ((text[i]) == '!' || (text[i]) == '?' || (text[i]) == '.')
        {
            sentance++;
        }
        
    
         
        float l = (letter / word) *100.00; //average number of letters per 100 words
        float s = (word / sentance) * 100.00; //average number of words per sentance
        float index = 0.0588 * l - 0.296 * s - 15.8; 
        int round_index = round(index);
        
         if (round_index < 16 && round_index > 1)
        {
            printf("Grade %i \n", round_index);
        } 
        else if (round_index >= 16) 
        {
            printf("Grade 16+ \n") ;
        }
        else if (round_index < 1) 
        {
            printf("Before Grade 1 \n") ;
        }
    }

【问题讨论】:

  • 不要使用float;使用doublefloat 是一种有限范围/精度的浮点类型,主要用于在大型数组中节省存储空间。
  • #include &lt;string.h&gt; 引入了一个标准 ISO C 标头,其中包含 strlenmemcpy 等函数的声明。在&lt;cs50.h&gt; 标头中有一个get_string,而不是在&lt;string.h&gt;
  • . 字符不一定结束一个句子。它以i. d.Mr. 等缩写形式出现。如果文本严格遵循某些约定,那么您可以指望. 后跟至少两个空格(或出现在数据末尾)作为句子结束符。
  • n = strlen(text); - 你为什么要多次这样做

标签: c cs50


【解决方案1】:

您可能会陷入整数除法陷阱:letterwordsentance 都被声明为 int,因此整数除法已完成。

例子:

7 / 2 = 3
6 / 7 = 0 (when the second one is larger, you always get zero)

为了避免这种情况,您可以将letter 和/或word 和/或sentance 声明为浮点数。 (你只需要一个浮点数就可以强制进行浮点运算,但最好将它们全部声明为浮点数)

只说一句:为什么你还用float作为浮点数?现在大多数人都在使用double(不要问我为什么)。
抱歉,第二句话:sentance,不应该是sentence(带有“e”)吗? :-)

【讨论】:

  • 非常感谢 :) 我意识到我在做单词/句子而不是句子/单词,这似乎已经解决了问题,但感谢提示。
  • 不客气。如果我的回答有用或解决了您的问题,请点赞或接受(这就是本网站的运作方式)。
猜你喜欢
  • 2013-08-14
  • 1970-01-01
  • 2018-05-07
  • 2015-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-21
  • 1970-01-01
相关资源
最近更新 更多