A1088 Rational Arithmetic (20分)

一、技术总结

  1. 关键点就一个最大公约数函数,一个化简函数,在加一个输出函数;
  2. 对于化简函数,首先如果分数为负数,那么得保证分子是负数,为了输出要求;在一个就是化简,如果分子等于0,那么要将分母赋值为1,如果不为零那么就要进行约分,即使用gcd函数找到最大公约数即可
  3. 再就是输出函数,这个要按照题目的具体要求进行输出:
  • 一般就是如果有负数在最前和最后加上括号;
  • 如果为整数那么直接输出分子即可;
  • 如果分子大于分母要输出假分式;
  • 如果本身是真分式,则输出真分式;

二、参考代码

#include<iostream>
#include<algorithm>
using namespace std;
typedef long long ll;
ll gcd(ll a, ll b){
	return !b ? a : gcd(b, a % b);
}
ll lcm(ll a, ll b){
	return a * gcd(a, b) / b;
}
struct Fraction{
	ll up, down;
}a, b;
Fraction reduction(Fraction result){
	if(result.down < 0){//保证分子是负数 
		result.up = -result.up;
		result.down = -result.down;
	}
	if(result.up == 0){
		result.down = 1;
	}else{//如果分子不为0,进行约分 
		int d = gcd(abs(result.up), abs(result.down));
		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 - f1.down * f2.up;
	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 = 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(){
	scanf("%lld/%lld %lld/%lld", &a.up, &a.down, &b.up, &b.down);
	showResult(a);
	printf(" + ");
	showResult(b);
	printf(" = ");
	showResult(add(a, b));
	printf("\n");
	
	showResult(a);
	printf(" - ");
	showResult(b);
	printf(" = ");
	showResult(minu(a, b));
	printf("\n");
	
	showResult(a);
	printf(" * ");
	showResult(b);
	printf(" = ");
	showResult(multi(a, b));
	printf("\n");
	
	showResult(a);
	printf(" / ");
	showResult(b);
	printf(" = ");
	if(b.up == 0) printf("Inf");
	else showResult(divide(a, b));
	return 0;	
}
posted @ 2020-06-29 22:47  睿晞  阅读(152)  评论(0编辑  收藏  举报