• 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 编译选项。

  • 相关阅读:
    简单错误记录
    识别有效的IP地址和掩码并进行分类统
    爬虫必备—BeautifulSoup
    爬虫必备—requests
    Shellinabox安装及使用教程
    Django——REST framework
    SaltStack部署
    使用js在HTML中自定义字符串格式化方法
    3种上传图片并实现预览的方法
    Ajax
  • 原文地址:https://www.cnblogs.com/luyi07/p/14577508.html
Copyright © 2020-2023  润新知