这是一道经典的数学问题,可以使用递归或循环两种方法来解决。
递归方法:
假设第10天猴子有x个桃子吃,那么第9天猴子一定有(x + 1) * 2个桃子,以此类推,可以得到第1天猴子要有多少个桃子才能保证最后剩下1个。
代码如下:
#include <stdio.h>int eat_peach(int day);int main() {int day = 1;int num;printf("请输入猴子吃的天数:\n");scanf("%d", &day);num = eat_peach(day);printf("第%d天猴子摘了%d个桃子\n", day, num);return 0;
}int eat_peach(int day) {if (day == 10) {return 1;} else {int peach_num = (eat_peach(day+1) + 1) * 2;return peach_num;}
}
循环方法:
从第10天开始倒推,每天的桃子数就是前一天的桃子数加1后乘以2,最后推到第1天即可。
代码如下:
#include <stdio.h>int main() {int day = 1;int peach_num = 1;printf("请输入猴子吃的天数:\n");scanf("%d", &day);for (int i = 10; i > day; i--) {peach_num = (peach_num + 1) * 2;}printf("第%d天猴子摘了%d个桃子\n", day, peach_num);return 0;
}