求一函数

baby624love 2009-05-21 10:24:07
怎样用重载>>的方法输入复数,使能接受2,2+3i,5i,-8i,2-3i,i,-i这样的输入 ?
...全文
110 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
bitsjx 2009-05-22
  • 打赏
  • 举报
回复
复数里面有虚部没实部或者是有实部没虚部的话可以默认没有的那部分为0不行吗?
rivulettornado 2009-05-22
  • 打赏
  • 举报
回复

#include <iostream>
#include <string>
using namespace std;

class Complex
{
friend istream & operator >>(istream & ,Complex & );
public:
double real;
double imag;
Complex(){real =0;imag = 0;}
};

istream & operator >>(istream & in,Complex & obj)
{
string num;
in>>num;
double R = 0;
double I = 0;
int flag1 = 0;//0 实部 1 虚部
int flag2 = 0;
int len = num.length();
char temp;

if(num[0] == 'i')
{
R = 0;
I = 1;
obj.real = R;
obj.imag = I;
}
else if(num[0] == '-')
{
if(num.find("i",1,1) == -1)//负实数
{
for(int i = 1;i < len;i++)
{
temp = num[i];
R = R * 10 + (temp - '0');
}
obj.real = - R;
obj.imag = I;
}
else
{
if(num.find("+",1,1) == -1 && num.find("-",1,1) == -1)//负虚数
{
for(int i = 1;i < len - 1;i++)
{
temp = num[i];
I = I * 10 + (temp - '0');
}
obj.real = R;
obj.imag = - I;
}
else
{
for(int i = 1;i < len - 1;i++)
{
temp = num[i];
if(temp == '+' || temp == '-')
{
flag1 = 1;
flag2 = (temp == '+')?0:1;
if(i == len -2)
{
I = 1;
}
}
else if(flag1 == 0)
{
R = R * 10 + (temp - '0');
}
else
{
I = I * 10 + (temp - '0');
}
}
obj.real = - R;
obj.imag = (flag2 == 0)?I:-I;
}
}
}
else
{
if(num.find("i",1,1) == -1)//正实数
{
for(int i = 0;i < len;i++)
{
temp = num[i];
R = R * 10 + (temp - '0');
}
obj.real = R;
obj.imag = I;
}
else
{
if(num.find("+",1,1) == -1 && num.find("-",1,1) == -1)//正虚数
{
for(int i = 0;i < len - 1;i++)
{
temp = num[i];
I = I * 10 + (temp - '0');
}
obj.real = R;
obj.imag = I;
}
else
{
for(int i = 0;i < len - 1;i++)
{
temp = num[i];
if(temp == '+' || temp == '-')
{
flag1 = 1;
flag2 = (temp == '+')?0:1;
if(i == len -2)
{
I = 1;
}
}
else if(flag1 == 0)
{
R = R * 10 + (temp - '0');
}
else
{
I = I * 10 + (temp - '0');
}
}
obj.real = R;
obj.imag = (flag2 == 0)?I:-I;
}
}
}
return in;
}

int main()
{
Complex a;
cin>>a;
cout<<a.real<<"+"<<a.imag<<"i"<<endl;
}


这个可以实现基本的功能,输入的实部和虚部要求是整数,不能是小数。如果在输出的地方再做一下修改,可以输出形式的更好。
lzh9955 2009-05-22
  • 打赏
  • 举报
回复
UP
taodm 2009-05-22
  • 打赏
  • 举报
回复
C++标准库里不是有现成的complex嘛。
xiaoshi935 2009-05-22
  • 打赏
  • 举报
回复
其实没必要这样输入呀,你只要输入两个数就好了,然后用复数类complex,里面有两个私有数据。
这样的话,比方说你输入5,-4。那么最终你的存储的形式就是5+4i,这样的话就可以了。
或者你还是不满意的话,可以再输出的时候显示成5+4i的形式,没必要输入也这样吧。
如果你非要这样的话,不知道下面这样可以不可以,LZ可以试一下:

friend istream & operator >> (istream &, const complex & c) {
double a, b;
cin >> a;
cout << "+";
cin >> b;
cout << "i";
}
「已注销」 2009-05-21
  • 打赏
  • 举报
回复
我试 了 还是不行
rivulettornado 2009-05-21
  • 打赏
  • 举报
回复
说一下我认为应该有的步骤吧
(1)定义好复数类
(2)输入到一个复数对象,输入的内容可以按照字符串读取,逐步解析字符串的内容,判断出+ - 号,以及i来
(3)对应存储到复数的实部和虚部

65,211

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

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