用c++写一个复数的加法
时间: 2023-10-16 11:09:37 浏览: 34
#include <iostream>
using namespace std;
class Complex {
private:
double real; // 实部
double imag; // 虚部
public:
Complex(double r = 0, double i = 0) : real(r), imag(i) {}
Complex operator+(const Complex& c) const {
return Complex(real + c.real, imag + c.imag);
}
void print() const {
cout << "(" << real << ", " << imag << "i)" << endl;
}
};
int main() {
Complex c1(1, 2);
Complex c2(3, 4);
Complex c3 = c1 + c2;
c3.print(); // 输出:(4, 6i)
return 0;
}
相关问题
用c++写出复数的计算
可以使用结构体来表示复数,例如:
```c
typedef struct {
double real; // 实部
double imag; // 虚部
} complex;
// 复数加法
complex add(complex a, complex b) {
complex c;
c.real = a.real + b.real;
c.imag = a.imag + b.imag;
return c;
}
// 复数减法
complex sub(complex a, complex b) {
complex c;
c.real = a.real - b.real;
c.imag = a.imag - b.imag;
return c;
}
// 复数乘法
complex mul(complex a, complex b) {
complex c;
c.real = a.real * b.real - a.imag * b.imag;
c.imag = a.real * b.imag + a.imag * b.real;
return c;
}
// 复数除法
complex div(complex a, complex b) {
complex c;
double d = b.real * b.real + b.imag * b.imag;
c.real = (a.real * b.real + a.imag * b.imag) / d;
c.imag = (a.imag * b.real - a.real * b.imag) / d;
return c;
}
```
使用时,可以先定义两个复数:
```c
complex a = {1., 2.}; // 1+2i
complex b = {3., 4.}; // 3+4i
```
然后进行计算:
```c
complex c = add(a, b); // c = a + b = 4+6i
complex d = sub(a, b); // d = a - b = -2-2i
complex e = mul(a, b); // e = a * b = -5+10i
complex f = div(a, b); // f = a / b = .44+.08i
```
c++用类模板实现整数加法,小数加法,复数加法
好的,我可以为您提供这个类模板的实现:
```c++
#include <iostream>
#include <type_traits>
#include <complex>
template<typename T>
class Adder {
public:
static_assert(std::is_arithmetic<T>::value, "Adder only supports arithmetic types");
T operator()(T a, T b) const {
return a + b;
}
};
template<typename T>
class Adder<std::complex<T>> {
public:
std::complex<T> operator()(const std::complex<T>& a, const std::complex<T>& b) const {
return a + b;
}
};
int main() {
Adder<int> int_adder;
std::cout << int_adder(1, 2) << std::endl;
Adder<float> float_adder;
std::cout << float_adder(1.5, 2.5) << std::endl;
Adder<std::complex<double>> complex_adder;
std::cout << complex_adder(std::complex<double>{1.0, 2.0}, std::complex<double>{3.0, 4.0}) << std::endl;
return 0;
}
```
这个类模板可以支持整数加法、小数加法和复数加法。当使用 `Adder<T>` 时,如果 `T` 是算术类型(即 `int`、`float`、`double` 等),则使用 `operator()` 对两个数进行加法运算。如果 `T` 是复数类型,则使用复数的加法运算。