C++ 使用类来计算两个复数的和
在本文中,我们将编写一个程序来计算两个复数的和 ( a1 + ib1) 和 ( a2 + ib2) 使用类。
例如
输入: 4 + i5和8 + i9
在这里,a1=4,a2=8。将a1和a2相加,我们得到(8 + 4) = 12
另外,b1=5,b2=9。将b1和b2相加,我们得到(5 + 9) = 14
输出: 9 + i14
输入: 2 + i7和10 + i6
在这里,a1=2,a2=10。将a1和a2相加,我们得到(2 + 10) = 12
另外,b1=7,b2=6。将b1和b2相加,我们得到(7 + 6) = 13
输出: 12 + i13
类的构造
首先,我们将创建一个表示复数的类。观察可知,一个复数中有一个实数(a1)和一个虚数(b1)。
我们需要两个数据成员来表示复数。
下面是类的结构:
class Complex
{
public:
int real; // To store real part of complex number
int imaginary; // To store imaginary part of complex number
}
构造函数
该类Complex将有两个构造函数来初始化类的成员变量。
- 非参数化构造函数
我们需要一个非参数化构造函数来将数据成员的默认值初始化为零。
以下是非参数化构造函数的结构: Complex() { real = 0; imaginary = 0; }
* 参数化构造函数
我们需要一个非参数化构造函数来将数据成员初始化为主函数传递的值。
下面是参数化构造函数的结构
Complex(int r, int i)
{
real = r; // r is initialized during object creation
imaginary = i; // i is initialized during object creation
}
算法
对于两个复数相加,我们将创建两个Complex类的对象,并用相应的值进行初始化。之后,我们将创建一个第三个对象来存储结果。
C++代码
// C++ program to Add two complex numbers
#include
using namespace std;
class Complex {
public:
int real; // To store real part of complex number
int imaginary; // To store imaginary part of complex number
Complex()
{
// Initial values are zero
real = 0;
imaginary = 0;
}
Complex(int r, int i)
{
real = r; // r is initialized during object creation
imaginary = i; // i is initialized during object creation
}
Complex addComplexNumber(Complex C1, Complex C2)
{
Complex res; // result object of complex class
// adding real part of complex numbers
res.real = C1.real + C2.real;
// adding Imaginary part of complex numbers
res.imaginary = C1.imaginary + C2.imaginary;
// returning the sum
return res;
}
};
// Main Class
int main()
{
// First Complex number
Complex C1(4, 5);
// printing first complex number
cout << "Complex number 1 : " << C1.real
<< " + i" << C1.imaginary << endl;
// Second Complex number
Complex C2(8, 9);
// printing second complex number
cout << "Complex number 2 : " << C2.real
<< " + i" << C2.imaginary << endl;
// for Storing the sum
Complex C3;
// calling addComplexNumber() method
C3 = C3.addComplexNumber(C1, C2);
// printing the sum
cout << "Sum of complex number : "
<< C3.real << " + i"
<< C3.imaginary;
cout << endl
<< endl;
// Test for second input
// First Complex number
Complex A(2, 7);
// printing first complex number
cout << "Complex number 1 : " << A.real
<< " + i" << A.imaginary << endl;
// Second Complex number
Complex B(10, 6);
// printing second complex number
cout << "Complex number 2 : " << B.real
<< " + i" << B.imaginary << endl;
// for Storing the sum
Complex C;
// calling addComplexNumber() method
C = C.addComplexNumber(A, B);
// printing the sum
cout << "Sum of complex number : "
<< C.real << " + i"
<< C.imaginary;
}
输出
Complex number 1 : 4 + i5
Complex number 2 : 8 + i9
Sum of complex number : 12 + i14
Complex number 1 : 2 + i7
Complex number 2 : 10 + i6
Sum of complex number : 12 + i13
Time complexity
The time complexity is O(1) as we have to call the function addComplexNumber() to add the two complex numbers.