C++中的复数运算

目录

1、复数定义

2、复数的基本操作

C++中的复数操作需要引用头文件#include<complex>。

1、复数定义

        complex类。

#include<iostream>
#include <complex>
using namespace std;
int main()
{
	complex<double> Complex=3.3+1i;
	complex<double> Complex1(3.6,1.7);
	cout << Complex << endl;
	cout << Complex1 << endl;
	return 0;
}

2、复数的基本操作

方法功能
real获取复数的实部 
imag获取复数的虚部
abs获取复数的绝对值
norm获取复数的范数
conj获取复数的共轭
	complex<double> Complex=3.3+1i;
	complex<double> Complex1(3.0 + 1i);
	double r_Complex = Complex.real();
	double i_Complex = Complex.imag();
	complex<double> sub = Complex - Complex1;//两个复数相减
	cout <<"real part" << r_Complex <<endl;
	cout << "imag part" << i_Complex << endl;
	cout << sub << endl;

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是一个简单的 C++ 代码示例,用于计算两个复数的加法、减法和乘法运算。 ```cpp #include <iostream> using namespace std; struct Complex { double real, imag; }; Complex add(Complex a, Complex b) { Complex res; res.real = a.real + b.real; res.imag = a.imag + b.imag; return res; } Complex sub(Complex a, Complex b) { Complex res; res.real = a.real - b.real; res.imag = a.imag - b.imag; return res; } Complex mul(Complex a, Complex b) { Complex res; res.real = a.real * b.real - a.imag * b.imag; res.imag = a.real * b.imag + a.imag * b.real; return res; } int main() { Complex a, b, res; char op; cout << "Enter the first complex number: "; cin >> a.real >> a.imag; cout << "Enter the second complex number: "; cin >> b.real >> b.imag; cout << "Enter the operation (+, -, *): "; cin >> op; switch (op) { case '+': res = add(a, b); cout << "The result of addition is: " << res.real << " + " << res.imag << "i" << endl; break; case '-': res = sub(a, b); cout << "The result of subtraction is: " << res.real << " + " << res.imag << "i" << endl; break; case '*': res = mul(a, b); cout << "The result of multiplication is: " << res.real << " + " << res.imag << "i" << endl; break; default: cout << "Invalid operation." << endl; break; } return 0; } ``` 在此代码,我们定义了一个 `Complex` 结构体来表示复数。它包含实部和虚部两个成员变量。然后,我们定义了三个函数来执行复数的加法、减法和乘法运算。每个函数都接受两个 `Complex` 类型的参数,并返回一个 `Complex` 类型的结果。最后,我们在 `main()` 函数读入两个复数和一个运算符,并根据运算符调用相应的函数来计算结果。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值