C++ 超简单的复数类

003:超简单的复数类

总时间限制: 

1000ms

 

内存限制: 

65536kB

// 在此处补充你的代码

描述

下面程序的输出是:

3+4i 
5+6i

请补足Complex类的成员函数。不能加成员变量。

#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
class Complex {
private:
    double r,i;
public:
    void Print() {
        cout << r << "+" << i << "i" << endl;
    }
};
int main() {
    Complex a;
    a = "3+4i"; a.Print();
    a = "5+6i"; a.Print();
    return 0;
}

输入

输出

3+4i
5+6i

样例输入

样例输出

3+4i
5+6i

来源

Guo Wei

注意,这里显然是一个函数的重载操作,将字符串的形式的复数表示拆分为浮点数表示,使用了STL中string模板库中函数

#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
class Complex
{
private:
	double r, i;
public:
	void Print()
	{
		cout << r << "+" << i << "i" << endl;
	}

	Complex& operator = (const char* s)
	{
		string str = s;
		int pos = str.find("+", 0);
		string strReal = str.substr(0, pos);//分离出代表实部的字符串
		r = atof(strReal.c_str());//atof库函数能将const char*指针指向的内容转换成float
		string strImaginary = str.substr(pos + 1, str.length() - pos - 2);//分离出虚部代表的字符串
		i = atof(strImaginary.c_str());
		return *this;
	}
};

int main()
{
	Complex a;
	a = "3+4i";
	a.Print();
	a = "5+6i";
	a.Print();
	return 0;
}

 

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值