【发布时间】:2017-07-01 19:18:45
【问题描述】:
C 递归函数错误
我正在学习“实用 C 编程,第 3 版” 由 Steve Oualline 撰写,其中包含这项任务,以制作具有以下要求的程序。
练习 9-3:编写一个函数
count(number, array, length)计算number出现在array中的次数。该数组具有length元素。这 函数应该是递归的。编写一个测试程序来配合这个函数。
我在大约 15 分钟内编写了程序,但我的输出并不完全符合我的要求。代码如下:
#include <stdio.h>
int length;
int count(int num2count, int array[length], int size);
int main(void)
{
char check;
int i = 0;
long int num_to_be_counted;
int ans;
printf("Please enter the length of array:");
scanf("%d",&length);
long int numbers[length];
for(int i = 0; i != length; ++i) {
numbers[i] = 0;
}
printf("Enter the array:");
while( check != '\n') {
scanf("%li",&numbers[i]);
++i;
check = getchar();
}
printf("Enter the number to be counted in the array:");
scanf("%d",&num_to_be_counted);
for(int i = 0; i != length; ++i) {
numbers[i] = 0;
}
ans = count(num_to_be_counted,numbers,length);
printf("The number appears %d times in the array.",ans);
return 0;
}
int count(int num2count, int array[length], int size)
{
static int times = 0;
static int i = 0;
if ( array[i] == num2count) {
++times;
}
if(i == size) {
return times;
}
while( i != length ) {
++i;
count(num2count,array,length);
}
}
程序没有错误(逻辑错误除外),这是示例输入和输出
length = 4
numbers = 1 2 2 4
number_to_count = 2
Output: 4
该函数甚至不计算要计算的数字;它只返回数组的大小,例如在本例中为 4。
我们将不胜感激任何形式的帮助。
【问题讨论】:
-
提示:不要使用全局变量或
static变量。 -
@melpomene 请详细说明?
-
为什么在接受用户的数组中的所有值后将它们重新分配给
0? -
所以你在 15 分钟内编写了代码,并没有花一分钟来调试。我学习调试/测试比编写代码要花更长的时间。
-
我尝试运行您的代码并遇到分段错误。你可能想检查你的递归函数并将循环放在你检查
if(i == size)的地方在函数的开头
标签: c arrays function recursion