正文

[039] 猴子吃桃问题2006-03-19 12:37:00

【评论】 【打印】 【字体: 】 本文链接:http://blog.pfan.cn/wentao/11164.html

分享到:

<谭> 6.10

猴子第一天摘下若干桃子,当即吃了一半,还不过瘾,又多吃了一个。第二天早上又将剩下的桃子吃掉一半,又多吃了一个。以后每天早上都吃了前一天剩下的一半零一个。到第10天早上想再吃时,见只剩下一个桃子了。求第一天共摘多少桃子。

#include <stdio.h>
int   main()
{
    int prev ;     /* 前一天 */
    int next = 1 ; /* 后一天, 初值为第10天 */
    int i;
    for (i = 9; i >= 1; i--)
    {
        prev = (next + 1) * 2 ; /* next=prev-(prev/2+1) */
        next = prev;
    }
    printf("total=%d\n", prev);
    return 0;
}

运行结果:
====================
total=1534
====================

此题用倒推的办法,所以注意循环结束的条件。多数情况下用循环为递增方式,本题中用递减方式,因此是: i >= 1 。

分步验证如下:
#include <stdio.h>
int   main()
{
    int prev ;
    int next = 1 ;
    int i;
    for (i = 9; i >= 1; i--)
    {
        prev = (next + 1) * 2 ;
        printf("i=%d total=%-5d \n", i, prev);
        next = prev;
    }
    return 0;
}

运行结果: ( i 表示第几天)
===============================
i=9 total=4
i=8 total=10
i=7 total=22
i=6 total=46
i=5 total=94
i=4 total=190
i=3 total=382
i=2 total=766
i=1 total=1534
===============================

阅读(8780) | 评论(3)


版权声明:编程爱好者网站为此博客服务提供商,如本文牵涉到版权问题,编程爱好者网站不承担相关责任,如有版权问题请直接与本文作者联系解决。谢谢!

评论

评论人: 发布时间: 2010-05-06 12:21:00
呵呵,我这比较简单
#include "stdio.h"
main()
{
    int x=1,i;
     for(i=1;i<10;i++)       
        x=2*x+2;    
    printf("%d\n",x);
}
评论人:tar 发布时间: 2007-12-09 02:58:00
#include <stdio.h>
using namespace std;
int Peach(int d){//the number of peach of dth //day
if(d==1){ return 1;}//only one peach left
else return (1+Peach(d-1))*2 ; //the number of peaches
//"today" is ((half of next day)-1)
}
int main(){
printf("%d",Peach(10);
return 0;
评论人:tar 发布时间: 2007-12-09 02:57:00
我今天刚在百度看到一个猴子吃桃问题,我是用递归解决的,拿来共享一下。
您需要登录后才能评论,请 登录 或者 注册