自頂向下,逐漸求精是一種很典型的算法設計基本思想——分治在結構化程式設計方法上的應用。
自頂向下,逐漸求精的原則是:
自頂向下
程式設計時,應先考慮總體,後考慮細節;先考慮全局目标,後考慮局部目标。不要一開始就過多追求衆多的細節,先從最上層總目标開始設計,逐漸使問題具體化。
逐漸細化
對複雜問題,應設計一些子目标作為過渡,逐漸細化。
子產品化設計
一個複雜問題,肯定是由若幹稍簡單的問題構成。子產品化是把程式要解決的總目标分解為子目标,再進一步分解為具體的小目标,把每一個小目标稱為一個子產品。
![](https://img.laitimes.com/img/__Qf2AjLwojIjJCLyojI0JCLiQ3chVEa0V3bT9CX5RXa2Fmcn9CXwczLcVmds92czlGZvwVP9EUTDZ0aRJkSwk0LcxGbpZ2LcBDM08CXlpXazRnbvZ2LcRlMMVDT2EWNvwFdu9mZvw1bOJTYsx2RlZXUYpVd1kmYr50MZV3YyI2cKJDT29GRjBjUIF2LcRHelR3LcJzLctmch1mclRXY39jN1ADN1czMwIDOyETM3EDMy8CX0Vmbu4GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.jpg)
下面以洗衣機為例講解自頂向下,逐漸求精的結構化程式設計方法。
首先,給出頂的僞代碼。
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 long
water_injection(level)
while(waterLevel<level)
inject water
soak(time)
while(time_counter()<time)
wait()
time_counter()
time=lastTime
return time
motor_run(direction)
if(direction==right)
turn right
else if(direction==left)
turn left
else if(direction==stop)
stop
drain()
while(waterLevel>)
drain
dried()
for(rotateTimes=;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 long
water_injection(level)
while(waterLevel<level)
inject water
soak(time)
while(time_counter()<time)
wait()
wait(time)
timePre=time_counter()
while(time_counter()-timePre<time)
do nothing
time_counter()
time=lastTime
return time
motor_run(direction)
if(direction==right)
turn right
else if(direction==left)
turn left
else if(direction==stop)
stop
drain()
while(waterLevel>)
drain
dried()
for(rotateTimes=;rotateTimes<setRotateTimes;rotateTimes++)
motor_run(left)
halt()
stop
wait()
if(hasStopped)
return success
else
return failure
wash_clothes()
washTime=choose_mode()
water_injection(setWaterLevel)
soak(setWaitTime)
beginTime=time_counter()
while(time_counter()-beginTime<washTime)
motor_run(right)
wait()
motor_run(left)
wait()
drain()
dried()
if(halt())
sound "beebee"
else
sound "didi"
這就實作了一個洗衣機洗衣服的僞代碼程式。