7-17 爬动的蠕虫 (15point(s)).c

原题如下:

一条蠕虫长1寸,在一口深为N寸的井的底部。已知蠕虫每1分钟可以向上爬U寸,但必须休息1分钟才能接着往上爬。在休息的过程中,蠕虫又下滑了D寸。就这样,上爬和下滑重复进行。请问,蠕虫需要多长时间才能爬出井?

这里要求不足1分钟按1分钟计,并且假定只要在某次上爬过程中蠕虫的头部到达了井的顶部,那么蠕虫就完成任务了。初始时,蠕虫是趴在井底的(即高度为0)。
输入格式:

输入在一行中顺序给出3个正整数N、U、D,其中D<U,N不超过100。
输出格式:

在一行中输出蠕虫爬出井的时间,以分钟为单位。
输入样例:

12 3 1

输出样例:

11
Analysis of : worm does not break the ranks of the sliding distance and break down from the height of the difference should be as well, Min for the time variable.The following code :

//  date:2020/3/6
//  author:xiezhg5
#include <stdio.h>
int main(void)
{
    int n,u,d,t,h=0,r=0;          //h为蠕虫向上爬动的距离,r为蠕虫休息时向下滑动的距离 
    scanf("%d %d %d",&n,&u,&d);
    for(t=1;;t++)                 //构造一个死循环计数 
    {
        if(r==0)                 //表示蠕虫还未休息 
        {
            h=h+u;
            r++;
            if(h>=n)            //当蠕虫向上爬动的距离等于井的高度时 
            {
                printf("%d",t);
                break;         //终止本循环 
            }
        }
        else
        {
            h=h-d;            //当休息时向下滑动,向上爬动的距离应减少 
            r--;
        }
    }
    return 0;
}
发布了30 篇原创文章 · 获赞 10 · 访问量 272

猜你喜欢

转载自blog.csdn.net/qq_45645641/article/details/104694845
今日推荐