PAT B1034/A1088 有理数四则运算 (20分)

Note:

1 数据范围为int,但当两个分母相乘时, 最大可以达到long long ,所以如果使用int就会溢出, 得到“答案错误”

2 计算最大公约数时,计算的是分子分母 “绝对值” 的公约数, 否则会错误

3 除法,如果除数为0,应当特判输出“Inf”

4 最后一个除法算式后不要输出回车键,否则会有一个测试点 “格式错误 ”

问题描述:

本题要求编写程序,计算 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
#include
using namespace std;
typedef long long ll;
ll gcb(ll a, ll b){//求最大公约数 
	if(b == 0)
	    return a;
	else
	    return gcb(b, a % b);
}
struct Fraction{//定义有理数 
	ll up, down;
};

Fraction reduction(Fraction result){//化简 
	if(result.down < 0)
	{
		result.up = -result.up;
		result.down = -result.down;
	}
	if(result.up == 0)
	    result.down = 1;
	else{
		int d = gcb(abs(result.up), abs(result.down));//易错1计算分子分母绝对值的公约数 
		result.up /= d;
		result.down /= d;
	}
	return result;
}
Fraction add(Fraction f1, Fraction f2){//加 
    Fraction result;
    result.up = f1.up*f2.down + f1.down*f2.up;
    result.down = f1.down*f2.down;
    return reduction(result);
}
Fraction minu(Fraction f1, Fraction f2){//减 
	Fraction result;
	result.up = f1.up*f2.down - f2.up*f1.down;
	result.down = f1.down*f2.down;
	return reduction(result);
}
Fraction multi(Fraction f1, Fraction f2){//乘 
	Fraction result;
	result.up = f1.up*f2.up;
	result.down = f1.down*f2.down;
	return reduction(result);
}
Fraction divide(Fraction f1, Fraction f2){//除 
	Fraction result;
	result.up = f1.up*f2.down;
	result.down = f1.down*f2.up;
	return reduction(result);
}
void showResult(Fraction r){//输出分数r 
	r = reduction(r);
	if(r.up < 0)
	    printf("(");
	    
	if(r.down == 1)
	    printf("%lld", r.up);
	else if(abs(r.up) > r.down)
	    printf("%lld %lld/%lld", r.up/r.down, abs(r.up) % r.down, r.down);
	else
	    printf("%lld/%lld", r.up, r.down);
	    
	if(r.up < 0)
	    printf(")");
}
int main(){
	Fraction f1, f2;
	scanf("%lld/%lld %lld/%lld", &f1.up, &f1.down, &f2.up, &f2.down);
	showResult(f1);
	cout << " + ";
	showResult(f2);
	cout << " = ";
	showResult(add(f1, f2));
	cout << endl;
	
	showResult(f1);
	cout << " - ";
	showResult(f2);
	cout << " = ";
	showResult(minu(f1, f2));
	cout << endl;

	showResult(f1);
	cout << " * ";
	showResult(f2);
	cout << " = ";
	showResult(multi(f1, f2));
	cout << endl;
	
	showResult(f1);
	cout << " / ";
	showResult(f2);
	cout << " = ";
	
	if(f2.up == 0)//易错2 除法除数为0要特判 
	    cout << "Inf" << endl; 
	else
	    showResult(divide(f1, f2));//易错3 最后一个输出后无回车键,否则有一个测试点格式错误 
	return 0;
}

 

你可能感兴趣的:(PAT乙级,PAT甲级)