求助!

llcnllcn 2003-05-29 09:30:05
考虑复数计算问题:

形如Z=a+ib的数,(其中a和b为实数,i*i=-1)叫做复数。复数的计算规则如下:

(a+ib)+(c+id)=(a+c)+i(b+d)
(a+ib)-(c+id)=(a-c)+i(b-d)
(a+ib)×(c+id)=(ac-bd)+i(ad+bc)
ac+bd bc-ad
(a+bi)÷(c+id)=-------+i--------
c*c+d*d c*c+d*d

a+ib的共轭是a-ib

复数的模:(a*a+b*b)的开方

设计并实现一个类Complex,要求提供复数乘法、除法、求模(操作符为!)及求共轭(操作符为~)运算的方法,提供方便的输入及输出操作(重载<<及>>操作符)。设计main()函数,从磁盘文件中读取6个不同的复数,测试你的设计结果,将测试结果输出到屏幕上。磁盘文件中数据的存储格式示例如下:

23.4+i179.3
6.0-i7.5
81.95+i13.6
572.315-i91.46
41.2+i40.76
63.0-i204.97


...全文
69 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
snipersu 2003-05-29
  • 打赏
  • 举报
回复
#include<iostream>
using namespace std;
class Complex
{
private:
double real;
double imaginary;
public:
Complex():real(0),imaginary(0)
{
}
Complex(double r,double i):real(r),imaginary(i)
{
}
friend Complex operator+(const Complex& lhs,const Complex& rhs)
{
return Complex((lhs.real+rhs.real),lhs.imaginary+rhs.imaginary);
}
friend Complex operator-(const Complex& lhs,const Complex& rhs)
{
return Complex((lhs.real-rhs.real),lhs.imaginary-rhs.imaginary);
}
friend Complex operator*(const Complex& lhs,const Complex& rhs)
{
return Complex((lhs.real*rhs.real-lhs.imaginary*rhs.imaginary),(lhs.real*rhs.imaginary+lhs.imaginary*rhs.real));
}
friend Complex operator/(const Complex& lhs,const Complex& rhs)
{
return Complex((lhs.real*rhs.real+lhs.imaginary*rhs.imaginary)/(rhs.real*rhs.real+rhs.imaginary*rhs.imaginary),
(lhs.imaginary*rhs.real-lhs.real*rhs.imaginary)/(rhs.real*rhs.real+rhs.imaginary*rhs.imaginary));
}
friend ostream& operator<<(ostream& os,const Complex& c)
{
cout<<c.real;
if(c.imaginary<0)
{
os<<c.imaginary<<"i"<<endl;
}
else if(c.imaginary>0)
{
os<<"+"<<c.imaginary<<"i"<<endl;
}
return os;
}
};
OstrichFly 2003-05-29
  • 打赏
  • 举报
回复
同意pengzhenwanli的说法。标准库不仅实现了应有的功能,对于实际的程序作了更多的优化。除非特殊的用途,一般情况下我们自己写的在效率和正确性上不会超过标准库。
rvvd 2003-05-29
  • 打赏
  • 举报
回复
楼上说的对,你可以用标准库的complex,它已经做的非常好,你没有必要自己在写代码。
你可以找一本C++标准库的书,看看它如何实现complex,你会收益很多。
dragonlw 2003-05-29
  • 打赏
  • 举报
回复
呵呵,由于时间关系我写个大概。

#include<iostream>
using namespace std;
class complex
{
float real;
float imag;
public:
complex()
{real=0;imag=0;}
complex(float REAL,float IMAG)
{ real=REAL;imag=IMAG;}
void print(); //输出了
complex operator+( complex & c1,complex & c2)
{
return complex(c1.real+c2.real,c1.imag+c2.imag);
}
complex operator-(complex & c1,complex & c2)
{
return complex(c1.real-c2.real,c1.imag-c2.imag);
}
.
.
.
.
.
.
};
llcnllcn 2003-05-29
  • 打赏
  • 举报
回复
计main()函数,从磁盘文件中读取6个不同的复数,测试你的设计结果,将测试结果输出到屏幕上。

这一步该怎么写呢?
pengzhenwanli 2003-05-29
  • 打赏
  • 举报
回复
你可以直接使用标准库complex
你要是想实现,可以看一下标准库的源代码

69,335

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧