程式設計基礎/函式示例
外觀
以下虛擬碼和流程圖示例採用上一章的溫度程式,將功能分離到獨立的函式中,分別用於輸入、處理和輸出,如 GetFahrenheit、CalculateCelsius 和 DisplayResult。
作為獨立的函式,每個函式都充當一個微型程式,具有自己的輸入、處理和輸出。在您檢視以下程式碼時,請注意哪些函式具有引數(輸入)以及哪些函式具有返回值(輸出)。引數和返回值將在接下來的幾頁中討論。
| 函式 | 目的 | 引數(輸入) | 返回值(輸出) |
|---|---|---|---|
| Main | 主程式 | 無 | 無 |
| GetFahrenheit | 輸入 | 無 | 華氏度 |
| CalculateCelsius | 處理 | 華氏度 | 攝氏度 |
| DisplayResult | 輸出 | 華氏度,攝氏度 | 無 |
Function Main
... This program asks the user for a Fahrenheit temperature,
... converts the given temperature to Celsius,
... and displays the results.
Declare Real fahrenheit
Declare Real celsius
Assign fahrenheit = GetFahrenheit()
Assign celsius = CalculateCelsius(fahrenheit)
Call DisplayResult(fahrenheit, celsius)
End
Function GetFahrenheit
Declare Real fahrenheit
Output "Enter Fahrenheit temperature:"
Input fahrenheit
Return Real fahrenheit
Function CalculateCelsius (Real fahrenheit)
Declare Real celsius
Assign celsius = (fahrenheit - 32) * 5 / 9
Return Real celsius
Function DisplayResult (Real fahrenheit, Real celsius)
Output fahrenheit & "° Fahrenheit is " & celsius & "° Celsius"
End
Enter Fahrenheit temperature: 100 100° Fahrenheit is 37.7777777777778° Celsius