求大佬指點(diǎn)!
當(dāng)if后面沒有return?age時(shí),輸出的年齡為8歲,加上后年齡為18,求解釋
#include <stdio.h>?
int people(n)
{ ? int age;
? ? if(n==1){age=10;return age;}
? ? else
? ? {age=people(n-1)+2;
? ? ?return age; ?
? ? }
}
int main()?
{
? ? int fifthage=people(5);
printf("第5個(gè)人的年齡是%d歲", fifthage);?
return 0;
}
2017-11-04
我并不是很專業(yè),但你這個(gè)問題我覺得是這樣的:
people(5) --> people(4) --> people(3) --> people(2) --> people(1)
若沒有return age即表示到達(dá)遞歸出口時(shí)沒有返回值age=10;
people(1)=0 --> people(2)=0+2 -->......-->people(5)=0+2+2+2+2=8;
2017-11-04
遞歸函數(shù)
當(dāng)n-1=1時(shí)是最后一次執(zhí)行代碼應(yīng)該執(zhí)行if(n==1){age=10;return age;}的代碼
返回age=10;
最后要加上10;