蓝桥杯 复数计算

编程实现两个复数的运算。设有两个复数 和 ,则他们的运算公式为:

  要求:(1)定义一个结构体类型来描述复数。
  (2)复数之间的加法、减法、乘法和除法分别用不用的函数来实现。
  (3)必须使用结构体指针的方法把函数的计算结果返回。
  说明:用户输入:运算符号(+,-,*,/) a b c d.
  输出:a+bi,输出时不管a,b是小于0或等于0都按该格式输出,输出时a,b都保留两位。

输入:
  - 2.5 3.6 1.5 4.9
输出:
  1.00+-1.30i

setprecision控制输出流显示浮点数的有效数字个数 ,如果和fixed合用的话,可以控制小数点后有几位。
cout<<fixed<<setprecision(2)<<123.456<<endl;/*如果在这个位置就加上fixed的话,后面的输出全部都按照fixed处理
cout << setprecision(4)<< 3.1415926 << endl;//输出的结果是3.142
cout<<setprecision(3)<<12345.0<<endl;//输出的结果是 "1.23e+004 "
cout<<fixed<<setprecision(2)<<123.456<<endl;//输出的结果是123.46,要进行四舍五入
cout<<showpoint<<12345.0<<endl;//输出12345.00

#include <iostream>
#include <cstdio>
#include <iomanip>
using namespace std;
class complex{
private:
    double a,b;
public:
    complex(){};
    complex(double,double);
    double get_a(){return a;}
    double get_b(){return b;}
    friend complex operator+(complex,complex);
    friend complex operator-(complex,complex);
    friend complex operator*(complex,complex);
    friend complex operator/(complex,complex);
    friend ostream& operator<<(ostream&,complex);
};
complex::complex(double x,double y){
    a=x;
    b=y;
}
complex operator+(complex s,complex t){
    double a=s.get_a()+t.get_a();
    double b=s.get_b()+t.get_b();
    complex temp(a,b);
    return temp;
}
complex operator-(complex s,complex t){
    double a=s.get_a()-t.get_a();
    double b=s.get_b()-t.get_b();
    complex temp(a,b);
    return temp;
}
complex operator*(complex s,complex t){
    double a=s.get_a()*t.get_a()-s.get_b()*t.get_b();
    double b=s.get_a()*t.get_b()+s.get_b()*t.get_a();
    complex temp(a,b);
    return temp;
}
complex operator/(complex s,complex t){
    double a=s.get_a()*t.get_a()+s.get_b()*t.get_b();
    double b=t.get_a()*s.get_b()-s.get_a()*t.get_b();
    double cnt=t.get_a()*t.get_a()+t.get_b()*t.get_b();
    complex temp(a/cnt,b/cnt);
    return temp;
}
ostream& operator<<(ostream& os,complex x){
    os<<fixed<<setprecision(2)<<x.get_a()<<'+'<<x.get_b()<<'i';
    return os;
}
int main(){
    char ch;
    double a,b,c,d;
    while(cin>>ch>>a>>b>>c>>d){
        complex p(a,b);
        complex q(c,d);
        if(ch=='+') cout<<p+q<<endl;
        else if(ch=='-') cout<<p-q<<endl;
        else if(ch=='*') cout<<p*q<<endl;
        else cout<<p/q<<endl;
        getchar();
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值