我即将解决 CS50 课程的可读性任务。这应该成为一个对字母和单词进行计数的程序,以便在 Coleman-Liau 索引中使用它们。因此我想将计算字母的类的返回值除以 100 。太看看它是否有效,我通过 printf 输出该值。例如,如果我输入值Whatever,则应输出值0.08。但它却输出 0。
我将变量score定义为float,并对返回值与compute_score类的返回值执行相同的操作。我还使用相同的数据类型定义了除数和除数。我什至在占位符中指定应精确指定 2 位小数。 不幸的是,我想不出错误出在哪里。我会很高兴得到帮助。 您可以阅读下面的代码。
#include <cs50.h>
#include <ctype.h>
#include <stdio.h>
#include <string.h>
float compute_score(string text);
int main(void)
{
string text = get_string("Text: ");
float score = compute_score(text);
printf("%2.f", score);
}
float compute_score(string text)
{
float divider = 100.00;
float letter = 0;
for (int i = 0; i < strlen(text); i++)
{
if ((text[i] >= 'a' && text[i] <= 'z') || (text[i] >= 'A' && text[i] <= 'Z'))
{
letter++;
}
}
return letter / divider ;
}
float compute_score1(string text)
{
return letter / divider ;
}
在
printf
中,您需要输入 .2
。紧接着 %
之后的数字是“字段宽度”(如果数字少于数字,则用空格等填充)。 .
之后的数字是精度,因此这就是您想要的 2 的位置。如果您在 .
之后没有指定数字,它将被视为零,因此没有小数,这解释了您的结果。
printf("%.2f", score);