基础编程题目集 7-17 爬动的蠕虫 (15分)

在这里插入图片描述

方法一:

/*假设爬行一分钟,休息一分钟*/
#include <stdio.h>
int main()
{
    int n, u, d;                //井口高度,上爬量和下滑量
    int time = 0, distance = 0; //虫虫消耗的时间(分钟),距离井底的距离(寸)
    scanf("%i %i %i", &n, &u, &d);
    /**
      * 第1分钟,爬;
      * 第2分钟,滑;
      * 第3分钟,爬;
      * 第4分钟,滑;
      * ...
      * 时间为偶数,虫虫下滑;
      * 时间为奇数,虫虫上爬。
      */
    do
    {
        time++;
        if (time % 2 != 0)
        {
            distance += u;
        }
        else
        {
            distance -= d;
        }
    } while (distance < n);
    printf("%i\n", time);
    return 0;
}

方法二:

#include <stdio.h>
int main()
{
    int n, u, d, time = 0, H = 0;
    scanf("%d%d%d", &n, &u, &d);
    while (1)
    {
        H += u;
        time++;
        if (H >= n)
            break;
        H -= d;
        time++;
    }
    printf("%d\n", time);
    return 0;
}
发布了287 篇原创文章 · 获赞 117 · 访问量 8935

猜你喜欢

转载自blog.csdn.net/qq_44458489/article/details/105399919