• c++中的复数


    参考来源:http://c.biancheng.net/view/703.html
    1. 复数模板为 complex,include就可以用了,具体可以使用
    complex<float>, complex<double>, complex<longdouble>
    2. 加减乘除和普通的浮点数一样使用,包括 +=, -=, *=, /=。也可以判别两个复数是否相等。
    3. 模方,辐角主值,共轭:norm(z), arg(z), conj(z)
    参考代码如下

    #include<iostream>
    using namespace std;
    
    #include<complex>
    #include<cmath>
    
    int main(){
    
            complex<double> z1, z2;
            cout<<" Please in put a complex number 
    	";
            cin>>z1;// e.g. (3,4) means 3+4i
            cout<<" Please in put another complex number 
    	";
            cin>>z2;
            cout<<"complex number z1 = "<<z1<<endl;
            cout<<" Re(z1) = "<<z1.real()<<endl;
            cout<<" Im(z1) = "<<z1.imag()<<endl;
            cout<<" z1 + z2 = "<<z1+z2<<endl;
            cout<<" z1 - z2 = "<< z1-z2 <<endl;
            cout<<" z1 * z2 = "<< z1*z2 <<endl;
            cout<<" z1 / z2 = "<< z1/z2 <<endl;
            if( z1 == z2 )cout<<" z1 == z2 "<<endl;
            cout<<" norm of z1 = "<< norm(z1) <<endl;
            cout<<" arg of z1 = "<< arg(z1) <<endl;
            cout<<" conjugate of z1 = "<< conj(z1) <<endl;
            cout<<" exp(z1) = "<<exp(z1)<<endl;
    
            return 0;
    }
    

    运行结果为

     Please in put a complex number 
    	(3,4)
     Please in put another complex number 
    	(4,5)
    complex number z1 = (3,4)
     Re(z1) = 3
     Im(z1) = 4
     z1 + z2 = (7,9)
     z1 - z2 = (-1,-1)
     z1 * z2 = (-8,31)
     z1 / z2 = (0.780488,0.0243902)
     norm of z1 = 25
     arg of z1 = 0.927295
     conjugate of z1 = (3,-4)
     exp(z1) = (-13.1288,-15.2008)
    

    挺好用。
    补充:c++11标准与如下语句不兼容:

    complex<double> z = 1 + 2i;
    

    编译器会说 2i 是神马?所以用复数的时候得去掉 -std=c++11 编译选项。

  • 相关阅读:
    Spring的AOP深入理解
    枚举和注解学习笔记
    单例模式
    工厂设计模式
    网络编程
    多线程笔记
    IOI2021集训队作业
    计蒜客 mark
    51nod mark
    关于此博客
  • 原文地址:https://www.cnblogs.com/luyi07/p/14577508.html
Copyright © 2020-2023  润新知