A1088 Rational Arithmetic (20 分)

本文介绍了一个使用C++实现的分数运算程序,包括加、减、乘、除四种基本运算。程序通过定义结构体和函数,实现了分数的简化、运算和打印功能。此程序展示了C++的数据结构和算法应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <cctype>
using namespace std;
typedef long long ll;
int N;
struct Fra{
	ll up, down;
}f1, f2;
ll gcd(ll a, ll b){
	return b == 0 ? a : gcd(b, a%b);
}
Fra reduction(Fra f){
	ll d = gcd(f.up, f.down);
	f.up /= d; f.down /= d;
	if(f.down < 0){
		f.up = -f.up; f.down = -f.down;
	}	
	if(f.up == 0 && f.down != 0) f.down = 1;
	return f;
}
Fra add(Fra f1, Fra f2){
	Fra sum;
	sum.up = f1.up * f2.down + f2.up * f1.down;
	sum.down = f1.down * f2.down;
	return reduction(sum);
}
Fra minu(Fra f1, Fra f2){
	Fra sum;
	sum.up = f1.up * f2.down - f2.up * f1.down;
	sum.down = f1.down * f2.down;
	return reduction(sum);
}
Fra mult(Fra f1, Fra f2){
	Fra sum;
	sum.up = f1.up * f2.up;
	sum.down = f1.down * f2.down;
	return reduction(sum);
}
Fra divide(Fra f1, Fra f2){
	Fra sum;
	sum.up = f1.up * f2.down;
	sum.down = f2.up * f1.down;
	return reduction(sum);
}
void print(Fra f){
	int flag = 0;
	if(f.up < 0){
		flag = 1;
		printf("(-");
		f.up = -f.up;
	}
	if(f.down == 0) printf("Inf");
	else if(f.down == 1) printf("%lld", f.up);
	else if(f.up > f.down){
		printf("%lld %lld/%lld", f.up/f.down, f.up%f.down, f.down);
	}else printf("%lld/%lld", f.up%f.down, f.down);
	if(flag) printf(")");
}
int main(){
	scanf("%lld/%lld %lld/%lld", &f1.up, &f1.down, &f2.up, &f2.down);
	f1 = reduction(f1); f2 = reduction(f2);
	
	print(f1); printf(" + "); print(f2); 
	printf(" = "); print(add(f1, f2)); putchar('\n');
	
	print(f1); printf(" - "); print(f2); 
	printf(" = "); print(minu(f1, f2)); putchar('\n');
	
	print(f1); printf(" * "); print(f2); 
	printf(" = "); print(mult(f1, f2)); putchar('\n');
	
	print(f1); printf(" / "); print(f2); 
	printf(" = "); print(divide(f1, f2)); putchar('\n');
	return 0;	
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值