定义一个复数类Complex,复数的实部Real与虚部Image定义为私有数据成员。用复数类定义复数对象c1、c2、c3。友元函数add,sub,mul,div分别用于复数的加、减、乘、除法运算,用公有成员函数Dispaly()显示复数运算结果。在主函数中,实例化两个复数,并输入一个运算符,按照运算符选择相应的友远函数进行复数运算,然后输出结果。
1条回答 默认 最新
关注 这个问题唯一的难题就是运算法则
- 加法:
(a + bi) + (c + di) = (a + c) + (b + d)i
- 减法:
(a + bi) - (c + di) = (a - c) + (b- d)i
- 乘法:
(a + bi) * (c + di) = (a*c - b*d) + (b*c + a*d)i
- 除法:
(a + bi) / (c + di) = ((a*c + b*d) / (c*c + d*d)) + ((b*c - a*d) / (c*c + d*d))i
#include <iostream> using namespace std; class Complex { public: Complex(){Real = 0.0; Image = 0.0;} // 默认构造函数 Complex(double x, double y) : Real(x), Image(y) {} // 拷贝构造函数 ~Complex(){} friend Complex Add(const Complex& c1, const Complex& c2); friend Complex Sub(const Complex& c1, const Complex& c2); friend Complex Mul(const Complex& c1, const Complex& c2); friend Complex Div(const Complex& c1, const Complex& c2); void display(); private: double Real; double Image; }; Complex Add(const Complex& c1, const Complex& c2) { Complex m; m.Real = c1.Real + c2.Real; m.Image = c1.Image + c2.Image; return m; } Complex Sub(const Complex& c1, const Complex& c2) { Complex m; m.Real = c1.Real - c2.Real; m.Image = c1.Image - c2.Image; return m; } Complex Mul(const Complex& c1, const Complex& c2) { Complex m; m.Real = c1.Real * c2.Real - c1.Image * c2.Image; m.Image = c1.Real * c2.Image + c1.Image * c2.Real; return m; } Complex Div(const Complex& c1, const Complex& c2) { Complex m; m.Real = (c1.Real * c2.Real + c1.Image * c2.Image) / (c2.Real * c2.Real + c2.Image * c2.Image); m.Image = (c1.Image * c2.Real - c1.Real * c2.Image) / (c2.Real * c2.Real + c2.Image * c2.Image); return m; } void Complex::display() { cout << Real << " + " << Image << "i" << endl; } int main() { Complex c1(6, 8); Complex c2(2, 4); Complex c3; char c = 'a'; while (c != 'c') { cout << "Please input [+ - * /]: "; cin >> c; if (c == '+') { c3 = Add(c1, c2); c3.display(); } else if (c == '-') { c3 = Sub(c1, c2); c3.display(); } else if (c == '*') { c3 = Mul(c1, c2); c3.display(); } else if (c == '/') { c3 = Div(c1, c2); c3.display(); } else { cout << "Error character, pleae input again." << endl; } } return 0; }
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 4无用- 加法:
悬赏问题
- ¥30 STM32 INMP441无法读取数据
- ¥100 求汇川机器人IRCB300控制器和示教器同版本升级固件文件升级包
- ¥15 用visualstudio2022创建vue项目后无法启动
- ¥15 x趋于0时tanx-sinx极限可以拆开算吗
- ¥500 把面具戴到人脸上,请大家贡献智慧
- ¥15 任意一个散点图自己下载其js脚本文件并做成独立的案例页面,不要作在线的,要离线状态。
- ¥15 各位 帮我看看如何写代码,打出来的图形要和如下图呈现的一样,急
- ¥30 c#打开word开启修订并实时显示批注
- ¥15 如何解决ldsc的这条报错/index error
- ¥15 VS2022+WDK驱动开发环境