我已经用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") ;
}
}发布于 2020-11-21 01:37:50
您可能会陷入整数除法陷阱:letter、word和sentance都被声明为int,因此完成了整数除法。
示例:
7 / 2 = 3
6 / 7 = 0 (when the second one is larger, you always get zero)为了避免这种情况,您可以将letter和/或word和/或sentance声明为浮点数。(为了强制浮点运算,您只需要有一个浮点数,但最好将它们都声明为浮点数)
只有一句话:为什么你仍然使用float作为浮点数?现在大多数人都在使用double (别问我为什么)。
对不起,第二个备注:sentance,这不应该是sentence (带有一个"e")吗?:-)
https://stackoverflow.com/questions/64934105
复制相似问题