我是编程的初学者,我正在研究此问题:https://cs50.harvard.edu/x/2020/psets/2/readability/
这是我的代码:
#include <cs50.h>
#include <stdio.h>
#include <string.h>
int main(void)
{
string text = get_string("Text: ");
// L = (letters in total) / (words in total) * 100
// S = (sentences in total) / (words in total) * 100
int letters = 0; // amount of letters contained in the text.
int sentences = 0; // amount of sentences in the text.
int words = 0; // amount of words in the text.
float L;
float S;
float grade;
for (int i = 0, n = strlen(text); i < n; i++) // loop through each letter in this txt.
{
if ((text[i] >= 65 && text[i] <= 90) || (text[i] >= 97 && text[i] <= 122)) // check if the current byte is a letter.
{
letters++;
}
else if (text[i] == '.' || text[i] == '!' || text[i] == '?') // check if the current byte is the end mark of the sentence.
{
sentences++;
}
else if (text[i] == ' ') // check if the current byte is a space.
{
words++;
}
}
L = (float) letters / (float) words * 100;
S = (float) sentences / (float) words * 100;
grade = 0.0588 * L - 0.296 * S - 15.8;
printf("L = %f, S = %f\n", L, S);
printf("letters: %i\n", letters);
printf("words: %i\n", words + 1);
printf("sentences: %i\n", sentences);
printf("grade: %f\n", grade);
}
我认为我的代码在逻辑上是正确的,与其他代码相比我看不出任何区别。但是,当我尝试获取如下所示的L和S的值时会遇到麻烦:
L = (float) letters / (float) words * 100;
S = (float) sentences / (float) words * 100;
带有示例输入语句
恭喜!今天是你的好日子。您去了好地方! 你无处不在!
变量字母和单词应该为65和14,因此
L = (float) 65 / (float) 14 * 100;
正确答案应该是464.2,但我却得到了500.0。
#include <cs50.h> #include <stdio.h> #include <string.h> int main(void) { int a = 65; int b = 14; float c = (float) a / (float) b * 100; printf("%f\n", c); printf("%f\n", (float) a); printf("%f\n", (float) b); printf("%f\n", (float) a / (float) b); }
请帮助!我真的不知道如何解决问题!
答案 0 :(得分:1)
您没有在最后一句话中计算最后一个单词,因为它后面没有空格。
添加
words++;
在循环结束后计算最后一个单词。
由于在此处加1,因此在打印单词数时无需使用words + 1
。