【发布时间】:2020-12-19 22:41:54
【问题描述】:
#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <math.h>
int letters = 0;
int words = 0;
int sentences = 0;
int main(void)
{
string text = get_string("Text: ");
printf("\n");
for(int j = 0; j < strlen(text); j++)
{
if((text[j] >= 'a' && text[j] <= 'z') || (text[j] >= 'A' && text[j] <= 'Z'))
{
letters++;
}
if(text[j] == ' ')
{
words++;
}
if(text[j] == '.' || text[j] == '?' || text[j] == '!')
{
sentences++;
}
}
printf("Letters: %i\n", letters);
printf("Words: %i\n", words + 1);
printf("Sentences: %i\n", sentences);
float L = ((float)letters / (float)words) * 100;
float S = ((float)sentences / (float)words) * 100;
float result = round(0.0588 * L - 0.296 * S - 15.8);
printf("%f\n", L);
printf("%f\n", S);
printf("%f\n", result);
if(result < 1)
{
printf("Before Grade 1");
}
if(result == 1)
{
printf("Grade 1");
}
if(result == 2)
{
printf("Grade 2");
}
if(result == 3)
{
printf("Grade 3");
}
if(result == 4)
{
printf("Grade 4");
}
if(result == 5)
{
printf("Grade 5");
}
if(result == 6)
{
printf("Grade 6");
}
if(result == 7)
{
printf("Grade 7");
}
if(result == 8)
{
printf("Grade 8");
}
if(result == 9)
{
printf("Grade 9");
}
if(result == 10)
{
printf("Grade 10");
}
if(result == 11)
{
printf("Grade 11");
}
if(result == 12)
{
printf("Grade 12");
}
if(result == 13)
{
printf("Grade 13");
}
if(result == 14)
{
printf("Grade 14");
}
if(result == 15)
{
printf("Grade 15");
}
if(result >= 16)
{
printf("Grade 16+");
}
printf("\n");
}
文字:
Congratulations! Today is your day. You're off to Great Places! You're off and away!
结果:
Letters: 65
Words: 14
Sentences: 4
500.000000
30.769232
4.000000
Grade 4
我需要在我的代码中计算 '0.0588 * L - 0.296 * S - 15.8' 公式,但由于某种原因,它给了我一些文本的错误答案和一些文本的正确答案。在这个特定的例子中,它应该给我'Grade 3',但它给了我'Grade 4',如果我输入10年级的文本,它会给我'Grade 10'。 'L' 和 'S' 的计算是错误的,在这个例子中,它们应该是 L = 464.29 和 S = 28.57。我真的不知道我哪里出错了,有人可以帮助我吗?
【问题讨论】:
-
OT:您可以简单地使用
printf("Grade %d", result),而不是使用 16 次if (resul == ...) ...。想象一下,如果你有 100 分,你的代码会是什么样子。 -
你不应该在每次循环迭代时调用
strlen。计算一次并将其存储在变量中,因为您的字符串没有改变。
标签: arrays c formula cs50 readability