1088 Rational Arithmetic

#include<iostream>

#include<cstdlib>

using namespace std;

long long a,b,c,d;

//最大公约数

long long gcd(long long t1,long long t2){

if(t2==0){

return abs(t1);

}

return gcd(t2,t1%t2);

}

//进行格式化分数运算

void formatFaction(long long m,long long n){

if(n==0){//如果分母为0

cout<<"Inf";

return ;

}

if(m==0){//如果分子为0

cout<<"0";

return ;

}

//判断是否为负数

bool isNegative((m<0&&n>0)||(m>0&&n<0));

//取绝对值

m=abs(m);

n=abs(n);

//计算整数部分

long long integert=m/n;

//计算分子部分

long long numerator=m%n;

//如果是负数

if(isNegative){

cout<<"(-";

}

//如果有整数部分

if(integert!=0){

cout<<integert;

}

//如果分数为0

if(numerator==0){

if(isNegative){

cout<<")";

}

return;

}

//如果整数和分数都存在

if(integert!=0){

cout<<" ";

}

//约分分数部分

long long divisor=gcd(numerator,n);

numerator/=divisor;

n/=divisor;

//输出分数部分

cout<<numerator<<"/"<<n;

//输出符号结束

if(isNegative){

cout<<")";

}

}

int main(){

char slash;

//读取第一个分数

cin>>a>>slash>>b;

//读取第二个分数

cin>>c>>slash>>d;

//进行加法运算

formatFaction(a,b);

cout<<" + ";

formatFaction(c,d);

cout<<" = ";

formatFaction(a*d+b*c,b*d);

cout<<endl;

//进行减法运算

formatFaction(a,b);

cout<<" - ";

formatFaction(c,d);

cout<<" = ";

formatFaction(a*d-b*c,b*d);

cout<<endl;

//进行乘法运算

formatFaction(a,b);

cout<<" * ";

formatFaction(c,d);

cout<<" = ";

formatFaction(a*c,b*d);

cout<<endl;

//进行除法运算

formatFaction(a,b);

cout<<" / ";

formatFaction(c,d);

cout<<" = ";

if(c==0){

cout<<"Inf";

}else{

formatFaction(a*d,b*c);

}

cout<<endl;

return 0;

}

相关推荐
Nazarick14 分钟前
力扣LeetCode热题75题(1)
java·算法·leetcode·力扣
西西弗Sisyphus15 分钟前
C++ 最小 Agentic Loop 实现 - 回调函数系列 - 指针与内存地址(2)
开发语言·c++
16月6日-晴37 分钟前
斐波那契数列题解
算法·leetcode
郝学胜-神的一滴1 小时前
Effective Python 条款47:吃透惰性属性
大数据·开发语言·数据库·人工智能·python·算法·oracle
西西弗Sisyphus2 小时前
C++ 最小 Agentic Loop 实现 - 回调函数系列 - typedef 封装(4)
c++
笑鸿的学习笔记2 小时前
C++笔记之信号量和引用计数的概念是否等价?
java·c++·笔记
Keven_112 小时前
算法札记:有限差分
算法
忙里偷闲学python3 小时前
GK2A 林火蔓延预报算法说明
算法
我是伪码农3 小时前
11.21程序设计
数据结构·算法
Tisfy3 小时前
LeetCode 3561.移除相邻字符:栈(相邻相消)
算法·leetcode·字符串·题解·栈·相邻相消