我最近几天前写了我的研究生入学考试,考试中出现了以下问题。
当以任何正整数作为参数调用以下函数时,它会终止吗?它还打印任何东西吗?
void convert (int n)
{
if (n < 0)
printf ("%d", n);
else
{
convert (n/2);
printf ("%d", n%2);
}
}
根据我的说法,不会打印任何内容,因为控件永远不会到达 if 语句内部,而且 printf 语句位于 else block 下的函数调用之后。 n 的值永远不会低于 0,函数会一次又一次地调用自身,直到堆栈溢出。我的问题是代码会不会因为栈溢出异常终止?
最佳答案
由于基本条件n < 0
,代码不会以正整数参数终止。永远不会遇见。
递归调用 convert
用参数 n / 2
调用它,作为整数除法,将不可避免地达到零,但绝不会小于它。
例如,参数 10
:
call convert(10)
10 < 0 is false; enter the else branch
call convert(10 / 2)
5 < 0 is false; enter the else branch
call convert(5 / 2)
2 < 0 is false; enter the else branch
call convert(2 / 2)
1 < 0 is false; enter the else branch
call convert(1 / 2)
0 < 0 is false; enter the else branch
call convert(0 / 2)
0 < 0 is false; enter the else branch
call convert(0 / 2)
0 < 0 is false; enter the else branch
call convert(0 / 2)
0 < 0 is false; enter the else branch
它永远不会进入基本情况。
关于c - 栈溢出异常终止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54596837/