c语言 - CS50的可读性/ 如何使用我的函数?


#include <cs50.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <math.h>
int count_letters(string);
int count_words(string);
int count_sentences(string);
float l, w, s;
int main(void)
{
//Get text
string text = get_string("Text:");
//Get the length of text
int i = strlen(text);
//Coleman-Liau index
float L = 100.0f * (l / (float)w);
float S = 100.0f * (s / (float)w);
int index = round(0.0588 * L - 0.296 * S - 15.8);
if (index < 1)
{
printf("Before Grade 1n");
}
else if (index > 16)
{
printf("Grade 16+n");
}
else
{
printf("Grade %in", index);
}
}
int count_letters(string text)
{
//Letters start from 0
l = 0;
for (int i = 0, n = strlen(text); i < n; i++)
{
if (isalpha(text[i]))
{
l++;
}
}
return l;
}
int count_words(string text)
{
//Spaces + 1 equals to count of words
w = 1;
for (int i = 0, n = strlen(text); i < n; i++)
{
//Space equals to number 32 in ASCII Chart
if(text[i] == ' ')
{
w++;
}
}
return w;
}
int count_sentences(string text)
{
s = 0;
for (int i = 0, n = strlen(text); i < n; i++)
{
if(text[i] == '!' || text[i] == '.' || text[i] == '?')
{
s++;
}
}
return s;
}

索引总是相同的负数,所以我只能得到"Before Grade 1"输出,因为我没有使用任何我创建的函数。

我在我的代码下面创建了3个函数,但我不知道如何在main中使用它们。我希望我的函数能够计算文本中字母(l),单词(w)和句子(s)的计数,以便找到索引。你能帮我吗?

创建一个变量,然后调用函数。该函数返回的值(本例中希望是整数)将存储在其中。举个例子,

int l = count_letters(text);

对其他两个函数做同样的事情,你就完成了。也可以在Coleman-Liau索引表达式之前定义它。

还要删除那些不需要的全局变量(可能在第11行)。

最新更新