2019-05-25 23:48

c++程序编写运算符重构

#include
#include
#include
using namespace std;

class Fraction

{
private:
int _s, _m;
public:
void Print() { cout << _s << "/" << _m << endl; }
// 在此处补充你的代码
};

int main()
{
Fraction a;
a = "3/5"; a.Print();
a = "48/-72"; a.Print();
return 0;
}

3/5
-2/3

3/5
-2/3

• 点赞
• 写回答
• 关注问题
• 收藏
• 邀请回答

1条回答默认 最新

• blownewbee 2019-05-26 09:22
已采纳

如果问题得到解决，请点下我回答左上角的采纳和向上的箭头

``````#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;

class Fraction
{
private:
int _s, _m;
public:
void Print() { cout << _s << "/" << _m << endl; }
// 在此处补充你的代码
Fraction& operator=(char * s)
{
_s = 0;
_m = 0;
int sng = 1;
while (*s != '/')
{
if (*s == '-') { sng = -sng; s++; continue; }
_s *= 10;
_s += *s - '0';
s++;
}
s++;
while (*s != '\0')
{
if (*s == '-') { sng = -sng; s++; continue; }
_m *= 10;
_m += *s - '0';
s++;
}
int gcd = _s > _m ? _m : _s;
int i;
for (i = gcd; i >= 1; i--)
if (_s % i == 0 && _m % i == 0)
break;
gcd = i;
_m /= gcd;
_s /= gcd * sng;
return *this;
}
};

int main()
{
Fraction a;
a = "3/5"; a.Print();
a = "48/-72"; a.Print();
return 0;
}
``````
点赞 评论