写只使用递归的C函数 [英] writing C function using only recursion
问题描述
我想找出是否偶数的阵列中的总和等于奇数的和,仅使用递归并且没有任何附加的功能,除递归且无任何静态变量
如果奇数的和等于偶数的总和,函数返回1,否则返回0。所有阵列中的数字是非负
函数签名应该是这样的:
函数(无符号整数一个[],INT N)
到现在为止我已经写了以下内容:
函数(无符号整数一个[],INT N)
{
如果(N == 0)返回0;
?回报(一个[0]%2)((A [0] +功能(一个+ 1中,n-1)):( - 一个[0] +功能(一个+ 1,N-1));
}
此函数返回所需的总和,但不是问题的答案(它是1,如果是0,如果没有)。
是的,这是一个任务的一部分,但没有说不准附加功能我解决不了。
如果我们假设在计算中不溢出:
INT功能(无符号整数一个[],INT N){
如果(N GT; = 0)!返回功能(一个,-n-1);
如果(++ñ== 0)返回0;
返回功能(一个+ 1,N)+((一个[0]%2)-a [0]:一个[0]);
}
在第一次调用到函数中,
N
非负,体现了数组的大小。我们递归调用函数和逻辑否定的结果,算术否定N + 1
。一个否定的关闭让1
重新present0
在随后的调用,总和唇上的是正累积,和赔率是负积累。负
N
递增,直至达到0
。在负N
递归调用的结果是0
如果金额相等,否则返回非零值。在回归到最外面的呼叫,逻辑否定其翻转,使
1
如果总和是相等的,则返回和0
其他。
块引用>我会离开它作为一个练习与溢出妥善处理。
I want to find out if the sum of even numbers in the array is equal to the sum of odd numbers, using only recursion and without any additional functions, except recursion and without any static variables.
If the sum of odd numbers is equal to the sum of even numbers, the function returns 1, else it returns 0. All the numbers in the array are non negative.
The function signature should look like this:
function(unsigned int a[], int n)
Until now I have written the following:
function(unsigned int a[], int n) { if(n==0) return 0; return (a[0]%2)?((a[0]+function(a+1,n-1)):(-a[0]+function(a+1,n-1)); }
This function returns the total sum required but not the answer to the question (which is 1 if yes and 0 if no).
Yes this is a part of an assignment but I cannot solve it without additional functions that are not allowed.
解决方案If we assume no overflow in the calculations:
int function (unsigned int a[], int n) { if (n >= 0) return !function(a, -n-1); if (++n == 0) return 0; return function(a+1, n) + ((a[0] % 2) ? -a[0] : a[0]); }
On first call into the function, the
n
is nonnegative, and reflects the size of the array. We recursively call the function and logically negate the result, and arithmetically negaten+1
. The off by one negation allows-1
to represent0
On subsequent calls, the sum of evens are positively accumulated, and odds are negatively accumulated. The negative
n
is incremented until it reaches0
. The result of the recursive calls on the negativen
is0
if the sums are equal, and non-zero otherwise.On return to the outermost call, the logical negation flips it so that
1
is returned if the sums are equal and0
otherwise.I'll leave it as an exercise to appropriately deal with overflow.
这篇关于写只使用递归的C函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!