Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

การคืนค่าหลายค่าจากฟังก์ชัน C++

บทนำ

ใน C หรือ C++ เราไม่สามารถคืนค่าหลายค่าจากฟังก์ชันได้โดยตรง ในส่วนนี้เราจะดูวิธีใช้เทคนิคเพื่อคืนค่ามากกว่าหนึ่งค่า

เราสามารถคืนค่าหลายค่าได้โดยใช้วิธี "call by address" หรือ "call by reference" ในฟังก์ชันเรียกใช้ เราจะใช้ตัวแปรสองตัวเก็บผลลัพธ์ และฟังก์ชันจะรับพอยน์เตอร์ ดังนั้นต้องส่งที่อยู่ของข้อมูล

ตัวอย่างนี้จะแสดงวิธีสร้างฟังก์ชันที่คืนค่าผลหารและเศษจากการหารสองจำนวนจากฟังก์ชันเดียว

Call By Address

ตัวอย่างโค้ด

#include <iostream>
using namespace std;

void div(int a, int b, int *quotient, int *remainder) {
    *quotient = a / b;
    *remainder = a % b;
}

int main() {
    int a = 76, b = 10;
    int q, r;
    div(a, b, &q, &r);
    cout << "Quotient is: " << q << "\nRemainder is: " << r << "\n";
    return 0;
}

ผลลัพธ์

Quotient is: 7
Remainder is: 6

Call By Reference

ตัวอย่างโค้ด

#include <iostream>
using namespace std;

void div(int a, int b, int &quotient, int &remainder) {
    quotient = a / b;
    remainder = a % b;
}

int main() {
    int a = 76, b = 10;
    int q, r;
    div(a, b, q, r);
    cout << "Quotient is: " << q << "\nRemainder is: " << r << "\n";
    return 0;
}

ผลลัพธ์

Quotient is: 7
Remainder is: 6