为了说明这一点,这是我的编程II类的分级作业。我通常很容易接受新的编程概念,但是这个关于递归的特殊任务确实让我感到失望,我正在寻找一些正确的方向。下面是逐字分配和我目前已有的代码。
魔术植物
我们有一种神奇的植物,一旦它被种植,它就在第一年发芽并长出两片叶子。它的叶子每年翻倍,除了每隔三年它的叶子翻倍。类似于:

编写一个名为MagicPlant的类,它包含以下方法:
在驱动程序类中测试方法。
找出您的算法和数据结构可以处理的最大(最老的)植物。
这就是我得到的结果,我在最后一个要点上遇到了麻烦,在第二个问题上也有点混乱(但我的代码似乎很有效)。
我的当前代码不包括驱动程序类,因为它只是调用语句:
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;
}
}发布于 2017-11-02 14:39:47
我的tipp是用递归替换while-loop。因此,您没有局部变量,而是将该变量返回到方法(递归)中。
另外,我建议您为递归创建两个方法:
public int getAgeR(int leaves){
return getAgeR(1, leaves); // call overload with initial value
}
private int getAgeR(int age, int leaves){
// do your magic here
}发布于 2017-11-02 14:39:22
// Recursive method that returns the age of the plant
// given the number of leaves.
public int getAgeR(int leaves) {
if(leaves == 2) {
return 1;
}
if(leaves % 3 == 0) {
return getAgeR(leaves/3)+1;
} else {
return getAgeR(leaves/2)+1;
}
}这是数年的反义词。与其从一开始开始,你只需要从结束开始,并减少每一个循环循环。
https://stackoverflow.com/questions/47077299
复制相似问题