课堂小练习(complex类)

Posted dadadacy

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了课堂小练习(complex类)相关的知识,希望对你有一定的参考价值。

定义一个复数类Complex,使得下面的代码能够工作:

Complex c1(3,5);     //用复数3+5i初始化c1;

Compex c2=4.5;      //用实数4.5初始化c2

c1.add(c2);              //将c1与c2相加,结果保存在c1中

c1.show();               //将c1输出(这时的结果应该是7.5+5i)

cout<<c1.mod()      //c1.mod()对c1进行取模运算

 

 1 #include <iostream>
 2 #include <cmath>
 3 using namespace std;
 4 
 5 class Complex{
 6 public:
 7     Complex (double real0,double imaginary0);
 8     Complex (double real0);
 9     Complex (Complex &C);
10     void add(Complex c2);
11     void show();
12     double mod();
13 private:
14     double real;
15     double imaginary;
16     double sreal;
17     double simaginary;
18 };
19 
20 Complex::Complex (double real0,double imaginary0):real(real0),imaginary(imaginary0){
21 }
22 
23 Complex::Complex (double real0):real(real0),imaginary(0){
24 }
25 
26 Complex::Complex(Complex &c3):real(c3.real),imaginary(c3.imaginary){
27 }
28 
29 void Complex::add(Complex c2){
30     sreal=real+c2.real;
31     simaginary=imaginary+c2.imaginary;
32 }
33 
34 void Complex::show(){
35     cout<<sreal<<"+"<<simaginary<<"i"<<endl;
36 }
37 
38 double Complex::mod(){
39     double mod0;
40     mod0=sqrt(sreal*sreal+simaginary*simaginary);
41     return mod0;
42 }
43 
44 int main(){
45     Complex c1(3,5);
46     Complex c2(4.5);  //这里改为“Complex c2=4.5;”就出错,有没有什么办法呀
47     Complex c3(c1);
48     c1.add(c2);
49     cout << "c1 + c2 = ";
50     c1.show();
51     cout << "mod = ";
52     cout<<c1.mod()<<endl;
53     return 0;
54 }

运行截图

技术图片

 实验二评论链接

https://www.cnblogs.com/zuiyankh/p/10587674.html#4219118

https://www.cnblogs.com/qsxsc/p/10583875.html#4219112

https://www.cnblogs.com/yfwg/p/10594280.html#4219099

以上是关于课堂小练习(complex类)的主要内容,如果未能解决你的问题,请参考以下文章

课堂小练习: 设计定义并实现complex类

课堂小练习: 设计定义并实现Complex类

课堂小练习: 设计定义并实现Complex类

课堂练习

课堂练习

课堂练习