Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
有人可以向我解释一下吗。
public int bunnyEars(int bunnies) { if(bunnies == 0) { return 0; } return 2 + bunnyEars(bunnies - 1); }
在我看来,如果 bunnies 等于 2,答案将是 3 而不是 4。即使我知道答案应该是 4。
您可以手动展开递归以验证它确实为每个兔子添加了 2 个耳朵
bunnyEars(2) => 2 + bunnyEars(1) => 2 + (2 + bunnyEars(0)) => 2 + (2 + 0) => 4
bunnyEars(2) == 2 + bunnyEars(1) == 2 + (2 + bunnyEars(0)) == 2 + (2 + 0) == 4