【问题标题】:CS50 readability result issueCS50 可读性结果问题
【发布时间】:2021-09-26 18:20:03
【问题描述】:

我编写了以下代码来解决可读性实验室问题。 它编译得很好,没有问题。 问题出在结果中,由于未知原因,它总是将s_avg 计算为零。 s_avg is100字的平均句子数。

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

//prototypes
int count_letters (string text);
int count_words(string text);
int count_sent(string text);

int main(void)
{
    // get the user to prompt part of the story
    string story = get_string("Text: \n");
    
    //variables
    int letters = count_letters(story);
    int words = count_words(story);
    int sentences = count_sent(story);
    
    //show results
    printf("%i letter(s)\n",letters);
    printf("%i word(s)\n",words);
    printf("%i sentence(s)\n",sentences);
    
    // Calculate average number of letters & sentences per 100 words
    int l_avg = (letters/words)*100;
    int s_avg = (sentences/words)*100;
    
    // Calculate Coleman-Liau index
    int index = round(0.0588 * l_avg - 0.296 * s_avg - 15.8);
    
    // check grade level
    if(index<1)
    {
        printf("Before Grade 1\n");
    }
    else if(index>16)
    {
        printf("Grade 16+\n");
    }
    else
    {
        printf("Grade %i\n",index);
    }
}

//count the number of letters
int count_letters (string text)
{
    int l = 0;
    for(int i=0,n=strlen(text); i<n; i++)
    {

        if((text[i]>=97 && text[i]<=122)||(text[i]>=65 && text[i]<=90))
        {

            l++ ;
        }
    }
    return l;
}

//count the number of words
int count_words(string text)
{
    int w = 1;
    for(int i=0,n=strlen(text); i<n; i++)
    {
        if (text[i]==32)
        {
            w++ ;
        }
    }
    return w ;
}

//count the number of sentences
int count_sent(string text)
{
    int s=0;
    for(int i=0,n=strlen(text); i<n; i++)
    {
        if ((text[i]==46) || (text[i]==33) || (text[i]==63))
        {
            s++ ;
        }
    }
    return s;
}

我不知道为什么它一直将int s_avg = (sentences/words)*100; 计算为零。 我意识到使用 debug50 工具。

【问题讨论】:

  • 假设句子=2,单词=20。 2/20 = 0 因为您正在使用 ints。如果您想要浮点结果,请使用浮点变量或将至少一个值转换为浮点类型。
  • 这能回答你的问题吗? What is the behavior of integer division?
  • 请提取并提供minimal reproducible example。为此,请记住这里没有人可以访问“cs50.h”,这不是标准头文件。作为这里的新用户,也可以使用tour 并阅读How to Ask
  • 或许最好在 cs50.stackexchange.com 发帖

标签: c cs50


【解决方案1】:

要计算字母和句子的平均数量,请改用double 类型变量。

double l_avg = ((double)letters / (double)words)*100;
double s_avg = ((double)sentences / (double)words)*100;

【讨论】:

    【解决方案2】:

    C 中的整数除法产生一个整数,而不是浮点数。您必须将除数和除数显式转换为float

    int i = 5 / 4;
    printf("%d", i); // prints 1
    
    float f = (float)5 / (float)4;
    printf("%f", f); // prints 1.250000
    

    所以,int s_avg = (sentences/words)*100 应该是:

    float s_avg = (float)sentences / (float)words * 100;
    

    【讨论】:

    • 除数和被除数都不需要,只要一个就够了。
    猜你喜欢
    • 1970-01-01
    • 2022-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-24
    • 1970-01-01
    • 1970-01-01
    • 2020-09-24
    相关资源
    最近更新 更多