我正在尝试创建3个函数,一个用于计算单词,一个用于计数字母,另一个用于打印字母和单词的平均值。我在xcode中遇到错误我在最后一个函数(printing_average()
)printf ...
感谢您的帮助。
我的代码:
...main()
int num_of_words()
{
int userInput;
int numOfWords = 0;
while ((userInput = (getchar())) != EOF)
{
while (userInput != ' ')
{
if (userInput == ' ')
numOfWords++;
}
}
return numOfWords;
}
int num_of_letters()
{
int userInput;
int numberOfLetters = 0;
while ((userInput = (getchar())) != EOF)
{
if (ispunct(userInput) && numberOfLetters > 0)
{
numberOfLetters--;
}
else if(userInput == 'n' && numberOfLetters > 0)
{
numberOfLetters--;
}
else if (userInput == ' ' && numberOfLetters > 0)
{
numberOfLetters--;
}
else if (isdigit(userInput))
printf("please enter only characters:\n");
continue;
}
return numberOfLetters;
}
int printing_average()
{
printf("please enter couple of words:\n");
return printf("the average of number of letters and number of words is: %d", num_of_letters()/num_of_words());
}
答案 0 :(得分:2)
我没有尝试编译你的程序,但我会说这个逻辑不起作用:
while (userInput != ' ')
{
if (userInput == ' ')
numOfWords++;
}
像这样,numOfWords永远不会增加,所以在你的上一次打印中你将被除以零......
答案 1 :(得分:1)
回答你的实际问题:是的,你可以调用任意数量的函数作为printf调用的一部分。
如果您想要为字母和单词实际计算相同的单词集,则您的逻辑不起作用。每次调用“getchar()”时,它都会从输入缓冲区中取出一些东西。因此,对于第一次调用,将读取一些输入,直到看到EOF。此时,第二个函数被调用,它立即看到EOF,因此不会有任何字母/单词计数。
要解决此问题,您需要将代码重新排列为: 1.将所有输入收集到一个数组中,然后使用这两个函数来确定每个函数的数量。 2.编写一个新函数,在一个函数中计算两个事物的数量。
我更喜欢选项二。这是一个更简单的解决方案,如果输入非常大,也不会导致问题 - 当然,这需要一些时间,但您不需要存储所有内容,然后计算两次!