20201215-经典基础C语言题02-猴子吃桃

经典基础C语言题-猴子吃桃

题干

猴子吃桃问题:

猴子第一天摘下若干个桃子,当即吃了一半,还不过瘾,又多吃了一个。

第二天早上又将第一天剩下的桃子吃掉一半,有多吃了一个。

以后每天早上都吃了前一天剩下的一半零一个。

到第 10 天早上想再吃时,发现只剩下一个桃子了。

编写程序求猴子第一天摘了多少个桃子。

实现思路

总体

  1. 输入
  2. 处理
  3. 输出

详细

  1. 定义day,peach1,peach2为基本整型,并将day和peach1初值为9和1
  2. 使用while循环,由后一天推前一天的桃子数peach2
    1. 然后形成推递式
    2. 天数递减
    3. 直到天为1,此时的桃子数即第一天摘的桃子数
  3. 输出结果

示例代码

#include <stdio.h>
int main()
{
    
    
    int day;      // 当前天数
    int peach;    // 今天桃子数
    int prePeach; // 前一天桃子数

    day = 9;
    peach = 1;
    
    while (day > 0)
    {
    
    
        prePeach = (peach + 1) * 2; /*前一天的桃子数是今天桃子数加1后的2倍*/
        peach = prePeach;           /*每一个今天,都会变成前一天*/    
        day--;                      /*现在是第9天,直到第1天,往前递推*/
    }
    
    printf("the total is %d\n", prePeach); /* 输出桃子的总数*/
    
    return 0;
}

测试结果

PS E:\clangstudy\class08> cd "e:\clangstudy\class08\" ; if ($?) {
    
     gcc 'c2猴子吃桃.c' -o 'c2猴子吃桃.exe' -Wall -g -O2 -static-libgcc -std=c11 -fexec-charset=utf-8 } ; if ($?) {
    
     &'.\c2猴子吃桃' }
the total is 1534

重构代码,抽象出功能函数

#include <stdio.h>

int getPrePeach(int day, int peach);

int main()
{
    
    
    printf("the total is %d\n", getPrePeach(9, 1)); /* 输出桃子的总数*/
    return 0;
}


/* 
    输入天数和还剩的桃子数,得第一天的桃子数
 */
int getPrePeach(int day, int peach)
{
    
    
    int prePeach = 0;
    while (day > 0)
    {
    
    
        prePeach = (peach + 1) * 2; /*前一天的桃子数是今天桃子数加1后的2倍*/
        peach = prePeach;           /*每一个今天,都会变成前一天*/    
        day--;                      /*现在是第9天,直到第1天,往前递推*/
    }
    return prePeach;
}


测试结果

PS E:\clangstudy\class08> cd "e:\clangstudy\class08\" ; if ($?) {
    
     gcc 'c2猴子吃桃2.c' -o 'c2猴子吃桃2.exe' -Wall -g -O2 -static-libgcc -std=c11 -fexec-charset=utf-8 } ; if ($?) {
    
     &'.\c2猴子吃桃2' }
the total is 1534

猜你喜欢

转载自blog.csdn.net/matrixbbs/article/details/111244992