【问题标题】:Wrong Output in CS50 Pset2 ReadabilityCS50 Pset2 可读性中的错误输出
【发布时间】:2020-04-09 15:30:17
【问题描述】:

程序使用 Coleman-Liau 索引。它旨在输出理解文本所需的(美国)年级水平。公式为:

指数 = 0.0588 * L - 0.296 * S - 15.8

当我输入诸如hello there 之类的简单文本时,我的成绩等级较高,但如果我输入更复杂的文字,我的成绩等级较低。

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

 float letter = 0;
 float word = 1;
 float sentence = 0;

 int main(void)
{
  string text = get_string("Text: ");

  for (int i = 0; i < strlen(text); i++)
  {
      if ((text[i] >= 'a' && text[i] <= 'z') || (text[i] >= 'A' && text[i] <= 'Z'))
      {
          letter++;
      }
      else if (text[i] == ' ')
      {
          word++;
      }
      else if (text[i] == '.' || text[i] == '!' || text[i] == '?')
      {
          sentence++;
      }
  }
  printf("Letter:%f, Word:%f, Sentence:%f\n", letter, word, sentence);

  float L = letter/word * 100;
  float S = sentence/word * 100;
  float x = (0.0588 * L) - (0.296 * S) - 15.8;
  if (x < 16 && x >= 0)
  {
      printf("Grade Level: %i",(int) round(x));
  }
  else if (x > 16)
  {
      printf("Grade Level: 16+");
  }
  else 
  {
      printf("Before Grade 1");
  }

【问题讨论】:

  • 如果您的输入是"hello there",那么您的代码将计算零句。这肯定不对吧?
  • 确实如此。当我输入文本时,我肯定会使用“。” '!'或者 '?'结束句子,因为它们被写入程序中。

标签: c cs50


【解决方案1】:

如果你想计算字母,你应该检查字符是否是字母。 C 中有一个内置函数(在 ctype.h 库中)

isalpha() //the function returns non-zero if character is alphabetic.

要计算单词,您需要检查字符是否为空白。在同一个库中,您可以使用以下函数来检查。

isblank() //the function returns non-zero if character is blank.

您计算字母的功能可能无法正常运行。我会打印字母、单词、句子的数量,以查看您的代码是否正常运行。然后,计算指数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-24
    • 1970-01-01
    • 2020-12-17
    • 1970-01-01
    • 2022-07-01
    相关资源
    最近更新 更多