Ç递归函数错误不准确的输出
我学习“实用C语言编程,第三版” 由史蒂夫·林,它包含这种分配使得它具有以下要求的程序。
练习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.
任何形式的帮助将不胜感激。
提示:不要使用全局或静态变量。 – melpomene
@melpomene请详细说明? – Muneeb
为什么在您接受用户的数据后,您将数组中的所有值重新赋值为“0”? – GoodDeeds