“自顶向下,逐步求精”思想方法的介绍

来源:互联网 发布:电纸书 安卓 软件 编辑:程序博客网 时间:2024/06/06 09:46

  有时,我们需要编写一个功能复杂的大程序。没有头绪?无从下手?那是因为你没有采用“自顶向下,逐步求精”的思想方法。


什么是“自顶向下,逐步求精”的思想方法?

Top-down design
  A top-down approach (also known as stepwise design and in some cases used as a synonym of decomposition) is essentially the breaking down of a system to gain insight into its compositional sub-systems in a reverse engineering fashion.

这里写图片描述

  Top-down design 要求工作个体对所设计的系统要有一个全面的理解,然后从顶层开始,不间断地逐层向下分解任务,直到系统的所有模块都便于掌握。
  换句话来说,就是将复杂的大问题分解为相对简单的小问题,找出每个问题的关键、重点所在,然后用精确的思维定性、定量地去描述问题。
  其核心本质是”分解”。‘


“自顶向下,逐步求精”举例(描述洗衣机控制程序)

这里写图片描述


使用伪代码分解“正常洗衣”程序的大步骤。

set the water in >> soap the clothes >> wash the clothes >> dewatering the clothes >> stop the work
注水 >> 浸泡 >> 洗涤和漂洗 >> 脱水 >> 停机


进一步用基本操作、控制语句(IF、 FOR、 WHILE等)、变量与表达式,写出每 个步骤的伪代码

注水:
turn on the water_in_switch
set the water volume
while(water_input is less than the water volume)
 keep the water_in_switch open
while(water_input is more than the water volume or volume timeout)
  stop input water

浸泡
set the soaping time
for(set the left time is zero ;the left time is less than the setting time; increase the left time)
 keep the clothes soaping
if(the left time is equal to the setting time)
  begin to wash

洗涤和漂洗
set the washing times to 3
set the washing time to 20
for(set a to zero; a is less than setting times; add 1 to a;)
  if(the washing times is not the 1st time)
   pouring the water
   pouring in the new and clean water
do
  washing and motor runs
while(the pass time is less than the washing time)
pouring the water

脱水
set the motor run’s frequency
set the running time
while the past time is less than the running time
 keep the motor running in the setting frequency


提取一些共性功能模块(函数),简化“正常洗衣”程序,使程序 变得更利于人类理解和修改维护。

int wait(time)
set the waiting time
return the waiting time

int the washing(time)
set the washing time
return the washing time

int pour_out the water(timeout)
set the time
while the time is over
 stop pouring

int pour_in the water(volume,timeout)
set the time
while the time is over
 stop pouring


  以上就是“自顶向下,逐步求精”的思想方法的介绍与举例。合理利用该方法,会让你的编程更有效率,让你写出的代码更加条理。