首页 > 解决方案 > 在 CS50 可读性问题中获得意外结果

问题描述

在解决这个可读性问题时,我得到了一些奇怪的意外结果(预计 16 年级以上,获得 10 年级等),我无法弄清楚错误在哪里或如何解决它,请帮我弄清楚出错误。代码如下:

//includes
#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <math.h>

//global variables
int lc; //letter count
int wc; //word count
int sc; //sentence count
bool awc; //already word counted
double L; //average number of letters per 100 words
double S; //average number of sentences per 100 words
float index;

//function declaration
int count_letters(string x);
int count_words(string x);
int count_sentences(string x);

//main
int main(void)
{
    string text = get_string("text : ");
    count_letters(text);
    printf("%i letters\n", lc);
    count_words(text);
    printf("%i words\n", wc);
    count_sentences(text);
    printf("%i sentences\n", sc);

    L = lc / wc * 100.0f;
    S = sc / wc * 100.0f;

    index = (0.0588 * L) - (0.296 * S) - 15.8;

    if(index < 1)
    {
        printf("Before Grade 1\n");
    }
    else if(index >= 16)
    {
        printf("Grade 16+\n");
    }
    else
    {
        printf("Grade %i\n", (int) round(index));
    }
}


//functions
int count_letters(string x)
{
   lc = 0;
   for(int i = 0, n = strlen(x); i < n; i++)
   {
      if((x[i] >= 'a' && x[i] <= 'z') || (x[i] >= 'A' && x[i] <= 'Z'))
      {
          lc += 1;
      }
   }
   return lc;
}

int count_words(string x)
{
    wc = 0;
    awc = false;
    for(int i = 0, n = strlen(x); i < n; i++)
    {
        if((x[i] >= 'a' && x[i] <= 'z') || (x[i] >= 'A' && x[i] <= 'Z'))
        {
           if(awc == false)
           {
                wc += 1;
                awc = true;
           }
        }
        if(x[i] == ' ')
        {
            awc = false;
        }
    }
    return wc;
}

int count_sentences(string x)
{
    sc = 0;
    for(int i = 0, n = strlen(x); i < n; i++)
    {
        if(x[i] == '.' || x[i] == '!' || x[i] == '?')
        {
            sc += 1;
        }
    }
    return sc;
}

到目前为止,这些函数的字母、单词和句子的数量是正确的,所以我认为问题出在主要部分,可能与“L”和“S”的变量类型或索引公式有关,请帮助我找出问题所在。谢谢

以下是一些测试:句子(预期结果)

1.One fish. Two fish. Red fish. Blue fish. (Before Grade 1)
2.Harry Potter was a highly unusual boy in many ways. For one thing, he hated the summer holidays more than any other time of year. For another, he really wanted to do his homework, but was forced to do it in secret, in the dead of the night. And he also happened to be a wizard. (Grade 5)
3.A large class of computational problems involve the determination of properties of graphs, digraphs, integers, arrays of integers, finite families of finite sets, boolean formulas and elements of other countable domains. (Grade 16+)

标签: ccs50

解决方案


L = lc / wc * 100.0f;

错误的

L = 100.0f * lc / wc;

正确的。

当 的两个操作数/都是整数时,结果也是整数,所以5/3 == 1.


推荐阅读