第一章-实例7-猴子吃桃问题

一群猴子摘了一堆桃子,它们每天都吃当前桃子的一半且多吃一个,到了第10天就只剩下一个桃子。求原来有多少个

个人感觉自己的做法比较好

自己的做法:

//一群猴子摘了一堆桃子,它们每天都吃当前桃子的一半且多吃一个,到了第10天就只剩下一个桃子。求原来有多少个桃子
#include <stdio.h>
#include <stdlib.h>

int main()
{
    int count=0;
    int sum=0;
    int b=0;
    printf("请输入原来有多少个桃子:\n");
    scanf("%d",&count);
    printf("请输入一共吃了几次:\n");
    scanf("%d",&b);
    if(count<0)
    {
        printf("您输入的有误\n");
    }
    else{
        sum=account(count,b);
        printf("原来桃子个数为%d",sum);
    }

    return 0;
}

int account(count,b)
{
    int a=0,i=0;
    a=count;
    i=b;
    for(i=b;i>0;i--){
        a++;
        a=a*2;
    }
    return a;

}

标准答案:


#include <stdio.h>
#include <stdlib.h>

int main(int argc,char** argv)
{
	int total=0;		//记录桃子总数
	int eat_time=0;		//记录猴子在数桃子前吃了多少次桃子	

	printf("请输入最后剩余桃子数:");
	scanf("%d",&total);

	while(true)
	{
		printf("请输入数桃子之前猴子吃了多少次了?");
		scanf("%d",&eat_time);
		if(eat_time<0)
		{
			printf("您输入的次数有误!\n");
			continue;
		}
		else
			break;
	}

	while(eat_time>0)
	{
		total=2*(total+1);
		eat_time--;
	};

	printf("猴子总共的桃子数目为:%d\n",total);

	system("pause");
	return 0;
}
posted @ 2020-01-04 23:22  二师兄你在干嘛  阅读(293)  评论(0编辑  收藏  举报