<分区>
明确地说,这是我的编程 II 类(class)的评分作业。我通常很容易接受新的编程概念,但这个关于递归的特殊任务真的让我很吃力,我正在寻找正确方向的一些好的插入。下面是逐字的作业和我目前已有的代码。
魔法植物
我们有一种神奇的植物,一旦种下,它就会在第一年发芽并长出两片叶子。它的叶子每年翻一番,除了每三年它的叶子增加三倍。像这样的东西:
编写一个名为 MagicPlant 的类,其中包含以下方法:
- 返回给定植物年龄的叶子数量的方法
- 一种非递归方法,根据叶子的数量返回植物的年龄。
- 一种递归方法,根据叶子的数量返回植物的年龄。
在驱动类中测试方法。
找出您的算法和数据结构可以处理的最大(最古老)植物。
这就是我得到的,我在最后一个要点上遇到了麻烦,在第二个要点上也有点困惑(但我的代码似乎可以工作)。
我当前的代码不包括 Driver 类,因为它只是调用语句:
public class MagicPlant {
// Method that returns the number of leaves given
// the age of the plant.
public int getLeaves(int age) {
int leafCount = 1;
for (int i = 1; i <= age; i++) {
if (i % 3 != 0) {
leafCount *= 2;
} else {
leafCount *= 3;
}
}
return leafCount;
}
// Non-recursive method that returns the age of the plant
// given the number of leaves.
public int getAgeNR(int leaves) {
int age = 1;
while (leaves > getLeaves(age)) {
age++;
}
return age;
}
// Recursive method that returns the age of the plant
// given the number of leaves.
public int getAgeR(int leaves) {
return 0;
}
}