有一堆桃子,猴子第一天吃了其中的一半,并再多吃了一个。
以后每天猴子都吃其中的一半,然后再多吃一个。
当到第10天时,想再吃时(即还没吃),发现只有一个桃子了。
问题:最初共多少个桃子
思路分析 逆推:
1)规律就是 前一天的桃子 = (后一天的桃子 + 1)* 2(此处可列方程)
2)Peach函数的参数是day,意为计算第几天的桃子个数
//2024.07.09
import java.util.Scanner;
public class Peach {
public static void main(String[] args) {
T t1 = new T();
int res = t1.peach(1);
if (res != -1) {//再次用到了值不合法为-1这样的思想
System.out.println("The number of peaches on the first day:" + res);
}else{
System.out.println("day <1 or day > 10!");
}
}
}
class T {
public int peach(int day){
if (day == 10) {
return 1;
}else{
if (day >= 1 && day <= 9) {
return (peach(day + 1) + 1) * 2;
}else{
return -1;
}
}
}
}
运行结果截图: