跳轉到內容

程式設計基礎/函式示例

來自華夏公益教科書,開放的書籍,開放的世界

以下虛擬碼和流程圖示例採用上一章中的溫度程式,並將功能分離成獨立的函式,分別用於輸入、處理和輸出,例如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

Main function flowchart GetFahrenheit function flowchart CalculateCelsius function flowchart DisplayResult function flowchart

參考文獻

[編輯 | 編輯原始碼]
華夏公益教科書