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