我已经尝试了所有方法,但是我无法弄清楚代码中的错误。
让用户输入数字并计算字母
int main(void)
{
int letters = 0;
//Getting user input
string text = get_string("Text: ");
//Counting the letters
for (int i = 0; i < strlen(text); i++)
{
if (isalpha(text[i]))
{
letters++;
}
}
计算单词和句子
int words = 1;
//Checking the spaces and counting the words
for (int i = 1; i < strlen(text); i++)
{
if ((isspace(text[i])) && (isalpha(text[i+1])) )
{
words++;
}
}
int sentences = 0;
//Checking the symbols and counting the sentences
for (int i = 0; i < strlen(text); i++)
{
if (text[i] == '.' || text[i] == '!' || text[i] == '?')
{
sentences++;
}
}
然后应用公式
double L = 100.0 * letters / words;
double S = 100.0 * sentences / words;
double index = 0.0588 * L - 0.296 * S - 15.8;
int trueIndex = round(index);
if (trueIndex >= 1 && trueIndex <= 16)
{
printf("Grade %i\n", trueIndex);
}
else
{
if (trueIndex < 1)
{
printf("Before Grade 1\n");
}
if (trueIndex > 16)
{
printf("Grade 16+\n");
}
}
}
它给了我这个错误:预期为“ 8 \ n级”,而不是“ 9 \ n级”。我知道这与我如何处理浮点数有关,但我不明白这是怎么回事
答案 0 :(得分:0)
尝试从计数单词中删除(isalpha(text[i+1])
部分。 isalpha()
仅对字母字符(即a-z,A-Z)返回true。对于引号将返回false并且不计算该单词。
爱丽丝开始厌倦了她的姐姐坐在沙滩上 银行,无事可做:她曾经窥探过一两次 她姐姐正在读书的书,但没有照片或 ”和“ ”一本书的用途是什么,”爱丽丝想 “没有图片或对话吗?”
//Checking the spaces and counting the words
for (int i = 1; i < strlen(text); i++)
{
if (isspace(text[i]))
{
words++;
}
}
答案 1 :(得分:0)
也许这个障碍很麻烦:
//Checking the spaces and counting the words
for (int i = 1; i < strlen(text); i++)
{
if ((isspace(text[i])) && (isalpha(text[i+1])) )
{
words++;
}
}
特殊条件(isalpha(text[i+1]))
,您假设在这种情况下,空格后面将出现字母字符。但是在测试用例中,有些句子带有引号(“),并且不会被视为字母。因此,您不会将其视为单词。
应该是8年级但您返回9的测试句子是:
爱丽丝开始厌倦了她的姐姐坐在沙滩上 银行,无事可做:她曾经窥探过一两次 她姐姐正在读书的书,但没有照片或 爱丽丝想,其中的对话“以及书的用途是什么” “没有图片或没有对话?
我试图根据您的条件运行该程序,它实际上在该语句返回9。 TL; DR:删除空格后按字母顺序的检查,您会感到很满意。