PAT有理数四则运算 c++ 78行

https://pintia.cn/problem-sets/994805260223102976/problems/994805287624491008

算法笔记的答案

采用分数结构体 定义化简以及加减乘除的操作

#include 
#include     //abs()
using namespace std;
typedef long long ll;
struct fraction {
     
	ll up,down;
}a,b;
ll gcd(ll a,ll b) {
     
	return a%b == 0 ? b : gcd(b,a%b);
}
fraction reduce(fraction a) {
     
	if (a.down<0) {
     
		a.down=-a.down;
		a.up=-a.up;
	}
	if (a.up==0)
		a.down=1;
	else {
     
		int d=gcd(abs(a.up),abs(a.down));
		a.down/=d;
		a.up/=d;
	}
	return a;
}
fraction add(fraction a,fraction b) {
     
	fraction result;
	result.up=a.up*b.down+a.down*b.up;
	result.down=a.down*b.down;
	result=reduce(result);
	return result;
}
fraction minu(fraction a,fraction b) {
     
	fraction result;
	result.up=a.up*b.down-a.down*b.up;
	result.down=a.down*b.down;
	result=reduce(result);
	return result;
}
fraction multi(fraction a,fraction b) {
     
	fraction result;
	result.up=a.up*b.up;
	result.down=a.down*b.down;
	result=reduce(result);
	return result;
}
fraction divide(fraction a,fraction b) {
     
	fraction result;
	result.up=a.up*b.down;
	result.down=a.down*b.up;
	result=reduce(result);
	return result;
}
void printfrac(fraction a) {
     
	a=reduce(a);
	if (a.up<0) printf("(");
	if (a.down==1)
		printf("%lld",a.up);
	else if (abs(a.up)>a.down)
		printf("%lld %lld/%lld",a.up/a.down,abs(a.up)%a.down,a.down);
	else
		printf("%lld/%lld",a.up,a.down);
	if (a.up<0) printf(")");
}
int main()
{
     
	scanf("%lld/%lld %lld/%lld",&a.up,&a.down,&b.up,&b.down);
	a=reduce(a),b=reduce(b);
	printfrac(a);printf(" + ");printfrac(b);printf(" = ");printfrac(reduce(add(a,b)));
	printf("\n");
	printfrac(a);printf(" - ");printfrac(b);printf(" = ");printfrac(reduce(minu(a,b)));
	printf("\n");
	printfrac(a);printf(" * ");printfrac(b);printf(" = ");printfrac(reduce(multi(a,b)));
	printf("\n");
	printfrac(a);printf(" / ");printfrac(b);printf(" = ");
	if (b.up==0)
		printf("Inf");
	else printfrac(reduce(divide(a,b)));
}

PAT有理数四则运算 c++ 78行_第1张图片

你可能感兴趣的:(C++,PAT,c++)