猴子第一天摘下若干个桃子,当即吃了一半,还不瘾,又多吃了一个,第二天早上又将剩下的桃子吃掉一半,又多吃了一个。以后每天早上都吃了前一天剩下的一半零一个。到第10天早上想再吃时,见只剩下一个桃子了。求第一天共摘了多少。
解题思路: 可以从后往前依次递减来想 第一种 代码:
package src.stu.day03;
public class homework08 {
public static void main(String[] args) {
int sum =1;
for (int i = 9; i > 0; i--) {
sum = 2*(sum+1);
}
System.out.println("第一天共摘了多少"+sum+"个");
}
}
第二种: 从第一天开始 代码:
public static void main(String[] args) {
int total = 0; // 第一天的桃子数
int peach = 1; // 第10天的桃子数
for (int i = 2; i <= 10; i++) {
total = (peach + 1) * 2;
peach = total;
}
System.out.println("第一天共摘了 " + total + " 个桃子");
}
}