이 섹션에서는 C++에서 복소수를 만들고 사용하는 방법을 살펴봅니다. C++에서 복소수 클래스를 만들 수 있습니다. 이 클래스는 복소수의 실수 부분과 허수 부분을 멤버 요소로 보유할 수 있습니다. 이 클래스를 처리하는 데 사용되는 몇 가지 멤버 함수가 있습니다.
이 예제에서는 복소수를 올바른 형식으로 표시하는 함수인 하나의 복합 유형 클래스를 만들고 있습니다. 두 개의 복소수 등을 더하고 빼는 두 가지 추가 방법
예시
#include<iostream>
using namespace std;
class complex {
int real, img;
public:
complex() {
//default constructor to initialize complex number to 0+0i
real = 0; img = 0;
}
complex(int r, int i) {
//parameterized constructor to initialize complex number.
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;//addition for real part
res.img = c1.img + c2.img;//addition for imaginary part
return res;//the result after addition
}
complex sub(complex c1, complex c2) {
complex res;
res.real = c1.real - c2.real;//subtraction for real part
res.img = c1.img - c2.img;//subtraction for imaginary part
return res;//the result after subtraction
}
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