C++ 程式:建立帶引數和返回值的函式
任何使用函式的程式語言的程式碼都更加簡單、模組化,並且在除錯的同時更容易修改。函式是模組化程式碼中一個非常有益的組成部分。函式能夠接受引數並輸出結果。函式不一定要接受輸入,也不一定要總是產生結果。有很多情況下,函式只接受少量輸入,並且不返回任何內容。不會總是響應,也不會容忍爭議。本文將解釋如何建立使用函式的 C++ 程式,這些函式接受多個引數並在處理後產生結果。
帶引數和返回值的函式
要定義一個這樣的函式,它帶有一些引數並向呼叫函式(呼叫函式是呼叫我們函式以執行某些操作的函式)返回一個值,則返回型別必須是特定型別(而不是 void),並且引數列表中必須有一個給定的引數列表。
語法
<return type> function_name ( <type1> argument1, <type2> argument2, … ) {
// function body
}
在下面的示例中,我們將數字作為引數傳遞,然後計算給定數字的階乘,並返回結果。讓我們看看 C++ 中的演算法和實現。
演算法
- 定義一個函式 factorial(),它將 n 作為引數
- fact := 1
- 當 n > 1 時,執行以下操作:
- fact = fact * n
- n = n - 1
- 迴圈結束
- 返回 fact
- 函式體結束
- 呼叫 factorial() 並將 n 傳遞給它以查詢 n 的階乘
示例
#include <iostream> using namespace std; long factorial( int n ) { long fact = 1; while ( n > 1 ) { fact = fact * n; n = n - 1; } return fact; } int main() { cout << "Factorial of 6 is: "; long res = factorial( 6 ); cout << res << endl; cout << "Factorial of 8 is: "; res = factorial( 8 ); cout << res << endl; cout << "Factorial of 12 is: "; res = factorial( 12 ); cout << res << endl; }
輸出
Factorial of 6 is: 720 Factorial of 8 is: 40320 Factorial of 12 is: 479001600
另一個示例是使用函式檢查數字是否為迴文數。我們將一個數字作為引數傳遞,當它是迴文數時,函式將返回 true,當它不是迴文數時,將返回 false。
演算法
- 定義一個函式 solve(),它將 n 作為引數
- sum := 0
- temp = n;
- 當 n > 0 時,執行以下操作:
- rem := n mod 10
- sum := (sum * 10) + rem
- n := floor of (n / 2)
- 迴圈結束
- 如果 sum 與 temp 相同,則
- 返回 true
- 否則
- 返回 false
- 結束 if 語句
示例
#include <iostream> #include <sstream> using namespace std; string solve( int n ) { int sum = 0; int temp = n; int rem; while( n > 0) { rem = n % 10; sum = (sum * 10) + rem; n = n / 10; } if( temp == sum ) { return "true"; } else { return "false"; } } int main() { cout << "Is 153 a palindrome? " << solve( 153 ) << endl; cout << "Is 15451 a palindrome? " << solve( 15451 ) << endl; cout << "Is 979 a palindrome? " << solve( 979 ) << endl; }
輸出
Is 153 a palindrome? false Is 15451 a palindrome? true Is 979 a palindrome? true
結論
在編寫程式碼時使用函式可以使程式碼模組化,並且在除錯或使用其他人的程式碼時有很多優勢。函式有不同的模式,有時從呼叫函式中獲取引數並向呼叫函式返回結果。有時它不接受任何輸入,但會返回值。在本文中,我們通過幾個示例瞭解瞭如何編寫既接受引數又向呼叫函式返回值的函式。使用函式非常簡單易於實現。在編寫程式碼時始終使用函式以減少許多應用程式中不必要的程式碼重複。
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP