【发布时间】:2018-06-09 23:03:05
【问题描述】:
#include <stdio.h>
void word(char a[100], int i, int *max, int *c)
{
printf("%d %d", max , c);
int length = 0;
while (i < strlen(a) && a[i] != ' ')
{
length++;
//printf("%c\n", a[i]);
i++;
}
if (a[i] == ' ' && i < strlen(a))
{
c++;
if (length > max)
max = length;
//printf("%d\n%d", max, c);
word(a, i + 1, max, c);
}
}
void main()
{
char a[100];
int max = 0, j, i = 0, c = 0;
scanf("%[^\n]s", &a);
word(a, 0, &max, &c);
printf("%d\n%d", c, max);
}
给定问题:给定一个带空格的字符串,编写一个算法和一个 C 程序来计算其中的单词数和最长单词的长度。例如,如果输入字符串是“我喜欢编程”,那么单词数是 3,最长字符串的长度是 11。
在递归函数word() 中通过引用传递变量max 和c 时遇到问题。变量未正确传递。我希望通过引用递归地传递变量,以便在每次递归调用时更新它们的值。我是stackoverflow的新手,如有错误请指正。
【问题讨论】:
-
printf("%d %d", max , c);-->printf("%d %d", *max , *c); -
提高编译器的警告级别,重新编译,阅读并理解警告,修复代码,重新开始。
标签: c function recursion pass-by-reference