首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >可读性返回负值

可读性返回负值
EN

Stack Overflow用户
提问于 2020-11-21 01:30:12
回答 1查看 106关注 0票数 0

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

代码语言:javascript
运行
复制
#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") ;
        }
    }
EN

回答 1

Stack Overflow用户

发布于 2020-11-21 01:37:50

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

示例:

代码语言:javascript
运行
复制
7 / 2 = 3
6 / 7 = 0 (when the second one is larger, you always get zero)

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

只有一句话:为什么你仍然使用float作为浮点数?现在大多数人都在使用double (别问我为什么)。

对不起,第二个备注:sentance,这不应该是sentence (带有一个"e")吗?:-)

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64934105

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档