我刚刚开始学习C语言,我有这个函数来解释,但我真的不明白。
int uknown(int a, int b)
{
if (b == 1) return a;
else return a + uknown(a, b - 1);
}
当我使用带有printf命令的函数时,例如:
#include <stdio.h>
int main()
{
printf ("Value = %i", uknown(3,4));
system("pause");
}
我的返回值为12.但是我很难理解计算是如何进行的。
答案 0 :(得分:5)
这是一个recursive方法,可以通过加法将两个整数相乘。该函数以递归方式调用
uknown(3,4) calls (since b != 1)
uknown(3,3) calls (since b != 1)
uknown(3,2) calls (since b != 1)
uknown(3,1) returns 3 to uknown(3,2) (since b == 1)
uknown(3,2) returns 3 + 3 = 6 to uknown(3,3)
uknown(3,3) returns 3 + 6 = 9 to uknown(3,4)
uknown(3,4) returns 3 + 9 = 12 to printf in main
答案 1 :(得分:2)
语句return a + uknown(a, b - 1);
返回以下步骤的值,
3 + unknown(3, 3);
3 + 3 + unknown(3, 2);
3 + 3 + 3 + unknown(3, 1);
3 + 3 + 3 + 3; // The last 3 is because of statement if (b == 1) return a;
= 12