以洗衣程序为例讲解自顶向下,逐步求精的结构化程序设计方法

来源:互联网 发布:最优化方法孙文瑜书 编辑:程序博客网 时间:2024/05/16 19:43

自顶向下,逐步求精是一种很典型的算法设计基本思想——分治在结构化程序设计方法上的应用。

自顶向下,逐步求精的原则是:

自顶向下
程序设计时,应先考虑总体,后考虑细节;先考虑全局目标,后考虑局部目标。不要一开始就过多追求众多的细节,先从最上层总目标开始设计,逐步使问题具体化。

逐步细化
对复杂问题,应设计一些子目标作为过渡,逐步细化。

模块化设计
一个复杂问题,肯定是由若干稍简单的问题构成。模块化是把程序要解决的总目标分解为子目标,再进一步分解为具体的小目标,把每一个小目标称为一个模块。

结构化程序设计


下面以洗衣机为例讲解自顶向下,逐步求精的结构化程序设计方法。


首先,给出顶的伪代码。

wash_clothes()//主程序


接着,将其细化求精。

第一次求精:

choose_mode()//选择模式
water_injection()//注水
soak()//浸泡
time_counter() // 返回当前时间计数,以秒为单位
motor_run(direction) // 电机转动。left左转,right右转,stop停
drain()//排水
dried()//甩干
halt() //停机,返回success 成功,failure 失败


第二次求精:

choose_mode()    input mode    if(mode==quickWashing)        return short    else if(mode==normalWashing)        return longwater_injection(level)    while(waterLevel<level)        inject watersoak(time)    while(time_counter()<time)        wait(1)time_counter()     time=lastTime    return timemotor_run(direction)     if(direction==right)        turn right    else if(direction==left)        turn left    else if(direction==stop)        stopdrain()    while(waterLevel>0)        draindried()    for(rotateTimes=0;rotateTimes<setRotateTimes;rotateTimes++)        motor_run(left)halt()     stop    if(hasStopped)        return success    else         return failure

第三次求精得到完整伪代码

choose_mode()    input mode    if(mode==quickWashing)        return short    else if(mode==normalWashing)        return longwater_injection(level)    while(waterLevel<level)        inject watersoak(time)    while(time_counter()<time)        wait(1)wait(time)    timePre=time_counter()    while(time_counter()-timePre<time)        do nothingtime_counter()    time=lastTime    return timemotor_run(direction)    if(direction==right)        turn right    else if(direction==left)        turn left    else if(direction==stop)        stopdrain()    while(waterLevel>0)        draindried()    for(rotateTimes=0;rotateTimes<setRotateTimes;rotateTimes++)        motor_run(left)halt()     stop    wait(60)    if(hasStopped)        return success    else         return failurewash_clothes()    washTime=choose_mode()    water_injection(setWaterLevel)    soak(setWaitTime)    beginTime=time_counter()    while(time_counter()-beginTime<washTime)        motor_run(right)        wait(5)        motor_run(left)        wait(5)    drain()    dried()    if(halt())        sound "beebee"    else        sound "didi"

这就实现了一个洗衣机洗衣服的伪代码程序。

阅读全文
0 0
原创粉丝点击