কমপ্লেক্স নম্বর ক্লাস বাস্তবায়ন
C++-এ বিল্ট-ইন কমপ্লেক্স নম্বর লাইব্রেরি (<complex>) আছে, কিন্তু নিচে কাস্টম ক্লাস বানানো দেখানো হয়েছে।
উদাহরণ কোড
#include <iostream>
using namespace std;
class complex {
int real, img;
public:
complex() : real(0), img(0) {}
complex(int r, int i) : real(r), img(i) {}
void set() { cin >> real >> img; }
void get() { cout << real << "+" << img << "i" << endl; }
void display() {
if (img < 0) {
if (img == -1) cout << real << "-i";
else cout << real << img << "i";
} else {
if (img == 1) cout << real << " + i";
else cout << real << " + " << img << "i";
}
cout << endl;
}
friend complex add(complex, complex);
friend complex sub(complex, complex);
};
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;
}
int main() {
complex n1(3, 2), n2(4, -3);
complex result = add(n1, n2);
result.display(); // 7 - i
result = sub(n1, n2);
result.display(); // -1 + 5i
return 0;
}
আউটপুট
The complex number is: 7-i The complex number is: -1 + 5i
নোট: বাস্তব প্রোজেক্টে #include <complex> এবং std::complex<double> ব্যবহার করা উচিত।