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

ฟังก์ชัน real() ใน C++

ฟังก์ชัน real() คืออะไร?

ฟังก์ชัน real() ใช้สำหรับ ดึงส่วนจริง (real part) ของจำนวนเชิงซ้อน (complex number) ฟังก์ชันนี้ส่งคืนส่วนจริงของจำนวนเชิงซ้อนและสามารถใช้ตั้งค่าส่วนจริงได้เช่นกัน ฟังก์ชัน real() เป็นฟังก์ชันของไฟล์หัวข้อ <complex>

ในจำนวนเชิงซ้อน a + bi ส่วน bi คือส่วนจินตภาพ (imaginary part) และ a คือ ส่วนจริง (real part) ของจำนวนเชิงซ้อน

ค่าที่ส่งคืน (Return)

ส่งคืนส่วนจริงของจำนวนเชิงซ้อนที่ระบุ

ไวยากรณ์ (Syntax)

template<class T> T real(const complex<T>& z);     // ฟังก์ชันอิสระ (non-member)
T complex<T>::real() const;                         // ฟังก์ชันสมาชิก (member function)
void complex<T>::real(T val);                       // ตั้งค่าส่วนจริง

พารามิเตอร์ (Parameters)

พารามิเตอร์ z แทนจำนวนเชิงซ้อนที่กำหนด

ตัวอย่างการทำงาน

Input:  จำนวนเชิงซ้อน = (14.7, 6.7)   → ส่วนจริง = 14.7
Input:  จำนวนเชิงซ้อน = (12, 12)       → ส่วนจริง = 12

แนวทางการเขียนโปรแกรม

  1. กำหนดจำนวนเชิงซ้อน
  2. พิมพ์จำนวนเชิงซ้อน
  3. พิมพ์ส่วนจริงของจำนวนเชิงซ้อนโดยใช้ฟังก์ชัน real()

ตัวอย่างโค้ดที่แก้ไขแล้ว (โค้ดต้นฉบับมีข้อผิดพลาดมาก)

// C++ code to demonstrate the working of real() function
#include <complex>
#include <iostream>
using namespace std;

int main() {
    // กำหนดจำนวนเชิงซ้อน
    complex<double> real_part(17.6, 4.5);
    cout << "Complex Number = " << real_part << endl;
    // พิมพ์ส่วนจริงโดยใช้ฟังก์ชัน real()
    cout << "Real part of complex number = " << real(real_part) << endl;
    // หรือใช้ member function
    cout << "Real part (member) = " << real_part.real() << endl;
    // ตั้งค่าส่วนจริงใหม่
    real_part.real(100.0);
    cout << "After setting real to 100: " << real_part << endl;
    return 0;
}

ผลลัพธ์ (Output)

Complex Number = (17.6,4.5)
Real part of complex number = 17.6
Real part (member) = 17.6
After setting real to 100: (100,4.5)

แก้ไขข้อผิดพลาดจากโค้ดต้นฉบับ:

  • ใช้ #include <complex> และ #include <iostream> แทน .h แบบเก่า
  • แก้ไข Complex<defines> → complex<double>
  • แก้ไขตัวพิมพ์ Using → using, Int → int
  • เพิ่มตัวอย่างการใช้ member function .real() และการตั้งค่า

ฟังก์ชันที่เกี่ยวข้อง: imag() สำหรับดึงส่วนจินตภาพ, abs() สำหรับหาค่าสัมบูรณ์ (magnitude), arg() สำหรับหามุม (phase angle)