自顶向下、逐步求精
自顶向下、逐步求精是计算机编程里面常用的思路
自顶向下
将大问题分解为各个小问题,再逐步求解
逐步求精
对于每个问题逐次细化,不断完善
例子
就如对一个洗衣机程序
先将他的洗衣这个大问题分为多个小问题:
选择 洗衣模式 输入 水位、时间
注水至预设水位
浸泡预设时间
漂洗预设时间 每个周期 电机转动左三秒、右三秒
排水至水位为0
脱水 电机快速转动 每周期左100秒右100秒 5个周期
关闭电源
然后再对每一个小问题细化出伪代码:
READ(water_line,soak_time,rinse_time)
WHILE getwatervolume()<water_line
waterinswitch(open)
ENDWHILE
waterinswitch(close)
SET now=timecounter()
WHILE timecounter()<=now+soak_time
ENDWHILE
SET now=timecounter()
WHLILE timecounter()<=now+rinse_time
SET now1=timecounter()
motorrun(left)
IF timecounter()==now1+3
motorrun(right)
ENDIF
IF timecounter()==now1+6
motorrun(stop)
ENDIF
ENDWHILE
WHILE getwatervolume()>0
wateroutswitch(open)
ENDWHILE
FOR i=1 to 5
now1=timecounter();
motorrun(left)
IF timecounter()==now1+100
motorrun(right)
ENDIF
IF timecounter()==now1+200
motorrun(stop)
ENDIF
ENDFOR
wateroutswitch(close)
halt(success)
最后还可以提取出一些模块
以便简化
FUNCTION wait(time)
SET now=timecounter();
WHILE timecounter()<=now+soak_time
ENDWHILE
ENDFUNCTION
FUNCTION 注水(volume,timeout)
SET now=timecounter();
WHILE getwatervolume()<volume
waterinswitch(open)
IF timecounter()now+timeout
halt(failure)
BREAK
ENDIF
ENDWHILE
waterinswitch(close)
ENDFUNCTION
FUNCTION 排水(timeout)
SET now=timecounter();
WHILE getwatervolume()>0
wateroutswitch(open)
IF timecounter()now+timeout
halt(failure)
BREAK
ENDIF
ENDWHILE
ENDFUNCTION