इस खंड में हम देखेंगे कि C++ में जटिल संख्याओं को कैसे बनाया और उपयोग किया जाए। हम C++ में एक जटिल संख्या क्लास बना सकते हैं, जो जटिल संख्या के वास्तविक और काल्पनिक भाग को सदस्य तत्वों के रूप में धारण कर सकती है। कुछ सदस्य फ़ंक्शन होंगे जो इस क्लास को संभालने के लिए उपयोग किए जाते हैं।
इस उदाहरण में हम एक जटिल प्रकार की क्लास बना रहे हैं, जटिल संख्या को सही प्रारूप में प्रदर्शित करने के लिए एक फ़ंक्शन। दो जटिल संख्याओं को जोड़ने और घटाने के लिए दो अतिरिक्त विधियां आदि।
उदाहरण
#include<iostream> using namespace std; class complex { int real, img; public: complex() { //डिफ़ॉल्ट कंस्ट्रक्टर जटिल संख्या को 0+0i पर आरंभ करने के लिए real = 0; img = 0; } complex(int r, int i) { //पैरामीटराइज्ड कंस्ट्रक्टर जटिल संख्या को आरंभ करने के लिए। real = r; img = i; } void set(); void get(); void display(); friend complex add(complex, complex); friend complex sub(complex, complex); }; void complex::set() { cout << "Enter Real part: "; cin >> real; cout << "Enter Imaginary Part: "; cin >> img; } void complex::get() { cout << "The complex number is: "<< real << "+" << img << "i" << endl; } void complex::display() { if(img < 0) if(img == -1) cout << "The complex number is: "<< real << "-i" << endl; else cout << "The complex number is: "<< real << img << "i" << endl; else if(img == 1) cout << "The complex number is: "<< real << " + i"<< endl; else cout << "The complex number is: "<< real << " + " << img << "i" << endl; } complex add(complex c1, complex c2) { complex res; res.real = c1.real + c2.real;//वास्तविक भाग के लिए जोड़ res.img = c1.img + c2.img;//काल्पनिक भाग के लिए जोड़ return res;//जोड़ के बाद परिणाम } complex sub(complex c1, complex c2) { complex res; res.real = c1.real - c2.real;//वास्तविक भाग के लिए घटाव res.img = c1.img - c2.img;//काल्पनिक भाग के लिए घटाव return res;//घटाव के बाद परिणाम } main() { complex n1(3, 2), n2(4, -3); complex result; result = add(n1,n2); result.display(); result = sub(n1,n2); result.display(); }
आउटपुट
The complex number is: 7-i The complex number is: -1 + 5i