㈠ 猴子吃桃問題(3種方法實現)
/*猴子吃桃*/
#include "malloc.h"
int day[10]; //每天的桃數
struct d{
int tao; //桃
struct d *yesterday; //昨天的指針
}today;
int all;
int Fun1()
{
int i;
day[9]=1;
for(i=8;i>-1;i--) //從最後一天算起
{
day[i]=(day[i+1]+1)*2;
}
printf("%d\n",day[0]); //輸出第一天的
}
int Fun2()
{
int i;
int tot;
struct d *p;
today.tao=1;
p=&today; //先到最後一天
i=1;
while(i<10)
{
tot=p->tao; //保存當前天的桃
p->yesterday=malloc(sizeof(struct d)); //分配空間,並當前天的前一天指向該地址
p=p->yesterday; //當前天變為前一天
p->tao=(tot+1)*2; //計算
i++;} //下一天
printf("%d\n",p->tao); //輸出
}
int Fun3(d)
int d;
{
if(d==1) return 1; //遞歸出口
else return (Fun3(d-1)+1)*2; //計算
}
int main()
{
Fun1();
Fun2();
all=Fun3(10);
printf("%d",all);
getchar();
}
㈡ 編程,猴子吃桃問題:猴子第一天摘下若干個桃子,當即吃了一半,還不過癮,又多吃了一個。第2天早上將
int day, x1, x2;
day = 9;
x2 = 1;
while (day > 0)
{
x1 = (x2 + 1) * 2; /*第一天的桃子是第二天桃子數加1後的2倍*/
x2 = x1;
day--; /*因為從後向前推所以天數遞減*/
Console.WriteLine("the total is {0}", x1);
Console.ReadKey();