1. 程式人生 > >用虛擬碼模擬洗衣機的運轉流程

用虛擬碼模擬洗衣機的運轉流程

今天的軟導課又學到了不少“騷操作”,其中就包括Pseudocode和Top-down design。
不如現在就藉著介紹洗衣機的運轉流程向大家介紹一下這兩個簡單的東西。

在這裡插入圖片描述

題目如下

仔細觀察您洗衣機的運作過程,運用Top-down設計方法和Pseudocode 描述洗衣機控制程式。
假設洗衣機可執行的基本操作如下: 
water_in_switch(open_close) // open 開啟上水開關,close關閉 
water_out_switch(open_close) // open 開啟排水開關,close關閉 
get_water_volume() //返回洗衣機內部水的高度
motor_run(direction) // 電機轉動。left左轉,right右轉,stop停
time_counter() // 返回當前時間計數,以秒為單位 
halt(returncode) //停機,success 成功 failure 失敗 

1)請使用虛擬碼分解“正常洗衣”程式的大步驟。包括注水、浸泡等 

2)進一步用基本操作、控制語句(IF、FOR、WHILE等)、變數與表示式,寫出每 個步驟的虛擬碼 

3)根據你的實踐,請分析“正常洗衣”與“快速洗衣”在使用者目標和程式上的異同。 你認為是否存在改進(創新)空間,簡單說明你的改進意見? 

4)通過步驟3),提取一些共性功能模組(函式),簡化“正常洗衣”程式,使程式 變得更利於人類理解和修改維護。

例如: 
wait(time) //等待指定的時間; 
注水(volume,timeout) //在指定時間內完成注水,否則停機; 
排水(timeout)。 
等子程式 

在這裡插入圖片描述

1.“正常洗衣”程式的大步驟

注水→浸泡→轉動→排水 (我這個洗衣機沒有脫水功能= =)

water_in_switch(open)
get_water_volume()
water_in_switch(close)
motorrun(left)
motorrun(right)
motorrun(stop)
water_out_switch(open)
get_water_volume()
water_out_switch(close)

2.進一步完善

從上面的虛擬碼中,我們可以知道這些大步驟跟現實生活的洗衣機還是有很大差距的,我們不如繼續進行改善。
下面我為它新增計時功能,各大步驟的時間限制功能,注水高度限制功能,結束音樂,以及故障停機功能。

check wrong
if success 
then
	record time
	water_in_switch(open)
	get_water_volume()
	
	if enough
	then
		tiemlimit
		water_in_switch(close)
		motorrun(left)
		motorrun(right)
		motorrun(stop)
		water_out_switch(open)
		get_water_volume()
		
		if empty
		then
			water_out_switch(close)
			return time
			music

3.結合生活實踐

現實生活中,洗衣機存在多種模式,比如“正常洗衣”與“快速洗衣”,這取決於使用者自己的時間安排,因此應該加入模式選擇的功能。

4.結合3中的觀點繼續完善

check wrong
if success 
then
	read mod    //mod1為正常洗衣 mod2為快速洗衣
	record time
	water_in_switch(open)
	get_water_volume()
	
	if enough
	then
		if mod=mod1 then timelimit=tiemlimit1
		if mod=mod2 then timelimit=tiemlimit2
		water_in_switch(close)
		motorrun(left)
		motorrun(right)
		motorrun(stop)
		water_out_switch(open)
		get_water_volume()
		
		if empty
		then
			water_out_switch(close)
			return time
			music

好了,整個設計洗衣機的過程終於告一段落了,希望大家能認識到Pseudocode和Top-down design的好處~~
(強行校徽水印)
在這裡插入圖片描述