我是一个新手,当然除了main之外,还需要实现不同的函数。我很难理解如何做到这一点,因为它对我来说并不可行。
这将是一个相当简单的解决方案,把所有的东西都放到main中,但我避免了这一点,由于说明中提示最好创建单独的函数,总体上我认为让main函数只实现你的各种函数更干净,对吗?
我遇到的问题是让各个函数能够使用其他变量,所以我设置了一些 globals。由于某些原因,我还发现当我想测试一切是否正常时,我不能使用变量的占位符,而必须打印函数本身的占位符,例如,用 printf("%d\n", letter_counter(text)
而不是 printf("%d\n", letter)
.
我现在遇到的问题是让我的coleman索引函数工作,我发现它不能打印S值,但L值工作正常。此外,如果我在main中调用字母、单词、& 句子函数(现在被注释掉了),这也会改变我的结果。
我很乐意接受你可能意识到的其他需要改进的一般指点。我想我只是总体上对让不同的功能相互配合感到困惑。
#include <stdio.h>
#include <cs50.h>
#include <ctype.h>
#include <string.h>
#include <math.h>
int letter_counter(string text);
int word_counter(string text);
int sentence_counter(string text);
void coleman_liau_formula(string text);
int letter;
int spaces;
int sentences;
int main(void)
{
string text = get_string("Text: ");
//letter_counter(text);
//word_counter(text);
//sentence_counter(text);
coleman_liau_formula(text);
}
// letter counter
int letter_counter(string text)
{
int i; //variable for looping through the string
for (i = 0; i < strlen(text); i++)
{
if (isalpha(text[i]) != 0)
{
letter++;
}
}
return letter;
}
// word counter
int word_counter(string text)
{
int i;
for (i = 0; i < strlen(text); i++)
{
if (isspace(text[i]) != 0)
{
spaces++;
}
}
if (letter == 0)
{
spaces = 0; // by default the program will output 1 word if no letters are inputted. this statement counters that.
return spaces;
}
else
{
return spaces + 1;
}
}
// sentence counter
int sentence_counter(string text)
{
int i = 0;
for (i = 0; i < strlen(text); i++)
{
if (text[i] == '.' || text[i] == '!' || text[i] == '?') //one flaw is that an occurence such as ellipsis would increase the sentence counter
{
sentences++;
}
}
return sentences;
}
void coleman_liau_formula(string text)
{
//float L = ((float) letter_counter(text) / (float) word_counter(text)) * 100;
//float S = ((float) sentence_counter(text) / (float) word_counter(text)) * 100;
//int index = round((0.0588 * L) - (0.296 * S) - 15.8);
/*if (index >=16)
{
printf("Grade 16+\n");
}
else if (index < 1)
{
printf("Before Grade 1\n");
}
else
{
printf("Grade %i\n", index);
}*/
printf("%i\n%i\n%i\n", letter_counter(text), word_counter(text), sentence_counter(text));
}
计数函数是累加的。也就是说,如果 word_counter
调用2次,它将 双重 的结果。这应该是你需要知道的所有进步。