PAT A1088 Rational Arithmetic

浪尽此生 提交于 2020-02-28 21:24:28

疑问

暂无

代码

//为什么是rational呢,因为分数都是有理数呀
#include<cstdio>
#include<algorithm>

using namespace std;

typedef long long ll;

struct Fraction{
	ll up;
	ll down;
};

Fraction x;
Fraction y; 

long long gcd(ll a,ll b){
	if(b == 0){
		return a;
	}else{
		return gcd(b,a%b);
	}
} 
 
void showResult(Fraction res){
	//1.如果是负数
	if(res.up < 0){
		printf("(");
		//如果是整数
		if(res.down == 1){
			printf("%lld",res.up);
		}else if(abs(res.up) > res.down){
			//如果是假分数
			printf("%lld ",res.up / res.down);
			printf("%lld/%lld",abs(res.up) % res.down,res.down); 
		}else{
			//是真分数
			printf("%lld/%lld",res.up,res.down); 
		} 
		printf(")");
	}else{
		//如果是整数
		if(res.down == 1){
			printf("%lld",res.up);
		}else if(abs(res.up) > res.down){
			//如果是假分数
			printf("%lld ",res.up / res.down);
			printf("%lld/%lld",abs(res.up) % res.down,res.down); 
		}else{
			//是真分数
			printf("%lld/%lld",res.up,res.down); 
		} 
	} 
} 

Fraction reduction(Fraction f){
	//如果分母是负数 
	if(f.down < 0){
		f.up = -f.up;
		f.down = -f.down;
	}
	//如果是0 
	if(f.up == 0){
		f.down = 1;
	}else{
		long long num = gcd(abs(f.up),abs(f.down));
		f.up = f.up / num;
		f.down = f.down / num;
	}
	return f; 
}

//加法 
void add(Fraction x,Fraction y){
	Fraction res;
	showResult(x);
	printf(" + ");
	showResult(y);
	printf(" = "); 
	
	res.up = x.up * y.down + y.up * x.down;
	res.down = x.down * y.down;
	
	res = reduction(res);
	
	showResult(res);
	
} 

//减法 
void sub(Fraction x,Fraction y){
	Fraction res;
	showResult(x);
	printf(" - ");
	showResult(y);
	printf(" = "); 
	
	res.up = x.up * y.down - y.up * x.down;
	res.down = x.down * y.down;
	
	res = reduction(res);
	
	showResult(res);
} 

//乘法 
void multi(Fraction x,Fraction y){
	Fraction res;
	showResult(x);
	printf(" * ");
	showResult(y);
	printf(" = "); 
	
	res.up = x.up * y.up;
	res.down = x.down * y.down;
	
	res = reduction(res);
	
	showResult(res);
} 

//除法 
void divide(Fraction x,Fraction y){
	Fraction res;
	showResult(x);
	printf(" / ");
	showResult(y);
	printf(" = "); 
	
	if(y.up == 0){
		printf("Inf");
	}else{
		res.up = x.up * y.down;
		res.down = x.down * y.up;
		res = reduction(res);
		showResult(res); 
	}
} 

int main(){
	scanf("%lld/%lld %lld/%lld",&x.up,&x.down,&y.up,&y.down);
	
	x = reduction(x);
	y = reduction(y);
	
	add(x,y);
	
	printf("\n");
	
	sub(x,y);
	printf("\n");
	multi(x,y);
	printf("\n");
	//注意除法要特判 
	divide(x,y); 
	
	return 0;
}

反思

  1. 我的代码好丑.jpg。
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!