나는 책에서 C를 배우려고 노력하고 있지만, 나를 위해 충분히 명확하게 설명되지 않은 것이있다.초보자가 재귀 함수에서 잃어버린
다음 코드
1) 재귀 함수를 사용하여 0 내지 99의 병 맥주를 카운트 다운한다. 그것이 내가이 카운트 다운하는 방법을 이해하고, 왜 다음 3)
... #more of same above
3 bottles of beer on wall, 3 bottles of beer
Take one down, pass around, 2 bottls of beer
2 bottles of beer on wall, 2 bottles of beer
Take one down, pass around, 1 bottls of beer
1 bottles of beer on wall, 1 bottles of beer
Take one down, pass around, 0 bottls of beer
There are no more bottles on the wall.
Put bottle in recycling, 1 empty bottles in bin
Put bottle in recycling, 2 empty bottles in bin
Put bottle in recycling, 3 empty bottles in bin
.... #pattern continues
을 재활용 병, 하나 하나를두고 "벽에 더 이상 병이 없습니다"인쇄 병에서의 일단 2) 더 이상 맥주 한 병은 없다고 말합니다. 그러나 병을 재활용하는 데 걸리는 코드 (printf)가 조건부의 else 부분에 있기 때문에 어떻게 호출되는지 이해하지 못합니다. 일단 병 수가 0에 도달하면 함수는 절대로 조건의 else 부분으로 되돌아 가지 않습니다.
질문 : 마지막 printf ("병을 재활용 중 ...")가 99 번 호출되고 어떻게 병을 하나씩 증가시킬 수 있습니까?
코드
void singTheSong(int numberOfBottles)
{
if(numberOfBottles == 0){
printf("There are no more bottles on the wall.\n");
}else {
printf("%d bottles of beer on wall, %d bottles of beer \n", numberOfBottles,numberOfBottles);
int oneFewer = numberOfBottles - 1;
printf("Take one down, pass around, %d bottls of beer \n", oneFewer);
singTheSong(oneFewer);
printf("Put bottle in recycling, %d empty bottles in bin \n", numberOfBottles);
}
}
int main(int argc, const char * argv[])
{
singTheSong(99);
return 0;
}
'printT' 문을'singTheSong (...) '함수의 시작 부분에 넣고 함수의 마지막 부분에 넣어서 무슨 일이 일어나고 있는지 이해하고 볼 수있게 해보십시오. – t0mm13b
수동 작업 작은 케이스 (2 또는 3)를 통해 – mfrankli
은 OP의 사용자 이름을 좋아할 수도 있습니다 ... – t0mm13b