[YTU]_2440( C++习题 复数类--重载运算符+,-,*,/)
生活随笔
收集整理的這篇文章主要介紹了
[YTU]_2440( C++习题 复数类--重载运算符+,-,*,/)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
題目描述
定義一個復數(shù)類Complex,重載運算符“+”,“-”,“*”,“/”,使之能用于復數(shù)的加、減、乘、除。運算符重載函數(shù)作為Complex類的成員函數(shù)。編寫程序,分別求兩個復數(shù)之和、差、積和商。
輸入
兩個復數(shù)
輸出
兩個復數(shù)之和、差、積和商
樣例輸入
3 4 5 -10樣例輸出
c1+c2=(8.00,-6.00i) c1-c2=(-2.00,14.00i) c1*c2=(55.00,-10.00i) c1/c2=(-0.20,0.40i)#include <iostream> #include <iomanip> using namespace std; class Complex { public:Complex();Complex(double r,double i);Complex operator+(Complex &c2);Complex operator-(Complex &c2);Complex operator*(Complex &c2);Complex operator/(Complex &c2);void display(); private:double real;double imag; }; Complex::Complex() {} Complex::Complex(double r,double i) {real=r;imag=i; } Complex Complex::operator+(Complex &c2) {return Complex(real+c2.real,imag+c2.imag);} Complex Complex::operator-(Complex &c2) {return Complex(real-c2.real,imag-c2.imag);} Complex Complex::operator*(Complex &c2) {return Complex(real*c2.real-imag*c2.imag,imag*c2.real+real*c2.imag);} Complex Complex::operator/(Complex &c2) {return Complex((real*c2.real+imag*c2.imag)/(c2.real*c2.real+c2.imag*c2.imag),(imag*c2.real-real*c2.imag)/(c2.real*c2.real+c2.imag*c2.imag));} void Complex::display() {cout<<'('<<real<<','<<imag<<"i)"<<endl; } int main() {double real,imag;cin>>real>>imag;Complex c1(real,imag);cin>>real>>imag;Complex c2(real,imag);cout<<setiosflags(ios::fixed);cout<<setprecision(2);Complex c3=c1+c2;cout<<"c1+c2=";c3.display();c3=c1-c2;cout<<"c1-c2=";c3.display();c3=c1*c2;cout<<"c1*c2=";c3.display();c3=c1/c2;cout<<"c1/c2=";c3.display();return 0; }《新程序員》:云原生和全面數(shù)字化實踐50位技術專家共同創(chuàng)作,文字、視頻、音頻交互閱讀
總結
以上是生活随笔為你收集整理的[YTU]_2440( C++习题 复数类--重载运算符+,-,*,/)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [YTU]_2443 ( C++习题 复
- 下一篇: [YTU]_2640( 编程题:运算符重