您的位置:首页 > 其它

1034. 有理数四则运算(20)

2015-09-08 20:27 253 查看
本题要求编写程序,计算2个有理数的和、差、积、商。

输入格式:

输入在一行中按照“a1/b1 a2/b2”的格式给出两个分数形式的有理数,其中分子和分母全是整型范围内的整数,负号只可能出现在分子前,分母不为0。

输出格式:

分别在4行中按照“有理数1 运算符 有理数2 = 结果”的格式顺序输出2个有理数的和、差、积、商。注意输出的每个有理数必须是该有理数的最简形式“k a/b”,其中k是整数部分,a/b是最简分数部分;若为负数,则须加括号;若除法分母为0,则输出“Inf”。题目保证正确的输出中没有超过整型范围的整数。
输入样例1:
2/3 -4/2

输出样例1:
2/3 + (-2) = (-1 1/3)
2/3 - (-2) = 2 2/3
2/3 * (-2) = (-1 1/3)
2/3 / (-2) = (-1/3)

输入样例2:
5/3 0/6

输出样例2:
1 2/3 + 0 = 1 2/3
1 2/3 - 0 = 1 2/3
1 2/3 * 0 = 0
1 2/3 / 0 = Inf

//写一个类储存分数,并且通过重载运算符,模拟纸面上的计算过程,在需要输出的时候算出转换成整数+真分数形式

#include <iostream>
#include <cstdio>
#include <cmath>

using namespace std;

long maxDivisor(long a, long b){
long t;
while (true){
t = a%b;
a = b;
b = t;
if (!t) return a;
}
}

long minMultiple(long a, long b){
return a*b / maxDivisor(a, b);
}

class Fraction{

public:
long a, b;
public:
Fraction(){};
Fraction(long _a, long _b, long _k = 0) :a(_a), b(_b){
getDivisor();
};

void getDivisor(){
//找出最大公约数,并且约分
long divsior = abs(maxDivisor(a, b));
a /= divsior;
b /= divsior;
//如果分子大于0分母小于0
if (a>0 && b<0){
a = -a; b = -b;
}

}

void prlongFra() const {
long k = a / b;
long tmpA = a%b;
if (k<0 && tmpA<0){
tmpA = -tmpA;
}

if (k<0 || (k == 0 && tmpA<0)) cout << "(";

if (k != 0){
cout << k;
if (tmpA != 0){
cout << " ";
}
}

if (tmpA != 0){
cout << tmpA;
if (b != 1){
cout << "/" << b;
}
}

if (k == 0 && tmpA == 0){
cout << 0;
}

if (k<0 || (k == 0 && tmpA<0)) cout << ")";
}

friend void operator +(const Fraction first, const Fraction second){
first.prlongFra();
cout << " + ";
second.prlongFra();
cout << " = ";
//找到最大公倍数,相加之后创建一个新的对象,然后输出
long b = minMultiple(first.b, second.b);
long multipleA = b / first.b;
long multipleB = b / second.b;
long a = first.a*multipleA + second.a*multipleB;
Fraction tmp(a, b);
tmp.prlongFra();
}

friend void operator -(const Fraction first, const Fraction second){
first.prlongFra(); cout << " - ";
second.prlongFra(); cout << " = ";

long b = minMultiple(first.b, second.b);
long multipleA = b / first.b;
long multipleB = b / second.b;
long a = first.a*multipleA - second.a*multipleB;
Fraction tmp(a, b);
tmp.prlongFra();
}

friend void operator *(const Fraction first, const Fraction second){
first.prlongFra(); cout << " * ";
second.prlongFra(); cout << " = ";
long a = first.a * second.a;
long b = first.b * second.b;
Fraction tmp(a, b);
tmp.prlongFra();
}

friend void operator /(const Fraction first, const Fraction second){
first.prlongFra(); cout << " / ";
second.prlongFra(); cout << " = ";

if (second.a){
long a = first.a * second.b;
long b = first.b * second.a;
Fraction tmp(a, b);
tmp.prlongFra();
}
else{
cout << "Inf";
}
}

};

int main(int argc, const char * argv[]) {

int a, b;
scanf("%d/%d", &a, &b);
Fraction first(a, b);
scanf("%d/%d", &a, &b);
Fraction second(a, b);

first + second; cout << endl;
first - second; cout << endl;
first * second; cout << endl;
first / second; cout << endl;

return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: