從 C++ 函式返回多個值
在 C 或 C++ 中,我們無法直接從函式返回多個值。在本節中,我們將看到如何使用一些技巧從一個函式返回多個值。
我們可以使用稱為“按地址呼叫”或“按引用呼叫”的方法從函式返回多個值。在呼叫函式中,我們將使用兩個變數來儲存結果,並且該函式將採用指標型別資料。因此,我們必須傳遞資料地址。
在這個示例中,我們將看到如何定義一個函式,該函式可以從一個函式返回兩個數字相除後的商和餘數。
按地址呼叫
示例
#include<iostream>
using namespace std;
void div(int a, int b, int *quotient, int *remainder) {
*quotient = a / b;
*remainder = a % b;
}
main() {
int a = 76, b = 10;
int q, r;
div(a, b, &q, &r);
cout << "Quotient is: "<< q <<"\nRemainder is: "<< r <<"\n";
}輸出
Quotient is: 7 Remainder is: 6
按引用呼叫
示例
#include<iostream>
using namespace std;
void div(int a, int b, int "ient, int &remainder) {
quotient = a / b;
remainder = a % b;
}
main() {
int a = 76, b = 10;
int q, r;
div(a, b, q, r);
cout << "Quotient is: "<< q <<"\nRemainder is: "<< r <<"\n";
}輸出
Quotient is: 7 Remainder is: 6
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP