c++之学习程序complex_1

来源:互联网 发布:网吧座位分布图软件 编辑:程序博客网 时间:2024/06/05 15:43

在寒假里把c++语法认真学了一遍,可一直没有机会练习,平时的程序都是用的c语言写的,忽然想练习一下c++程序,毕竟它比c语言要高一级,多练练没有坏处,用的还是c语言中的计算技巧,所以就找了本c++程序上机指导,看懂了写一下,加强理解。

刚写写一个书上的程序,可结果运行不对,以后再回来看吧,以我现在的能力还没有看出其中的错误在那。

#include<iostream>
using namespace std;
class complex
{
public:
 complex(){real=0;imag=0;}
 complex(double r,double i){real=r;imag=r;}
 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::operator +(complex &c2)//两个complex中前一个表示返回值,以前一直没有明白。
{
 complex c;
 c.real=real+c2.real;
 c.imag=imag+c2.imag;
 return c;
}
complex complex::operator -(complex &c2)
{
 complex c;
 c.real=real-c2.real;
 c.imag=imag-c2.imag;
 return c;
}
complex complex::operator *(complex &c2)
{
 complex c;
 c.real=real*c2.real-imag*c2.imag;
 c.imag=imag*c2.real+real*c2.imag;
 return c;
}
complex complex::operator / (complex &c2)
{
 complex c;
 c.real=(real*c2.real+imag*c2.imag)/(c2.real*c2.real+c2.imag*c2.imag);
 c.imag=(imag*c2.real-real*c2.imag)/(c2.real*c2.real+c2.imag*c2.imag);
 return c;
}
void complex::display()
{
 cout<<"("<<real<<","<<imag<<"i)"<<endl;
}
int main()
{
 complex c1(3,4),c2(5,-10),c3;
 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;

}

 输出结果:

(8,8i)

(-2,-2i)

(0,30i)

(06,0i)

错误的莫名其妙!!!!

原创粉丝点击