题目传送门<==戳这
1.这题分类原则特别重要,一不小心代码行数就会100+
2.输入比较巧妙,利用了scanf的格式化输入,而非字符串
3.将重复出现的操作写入函数内部,调用即可
直接上代:
#include <iostream>
#include <cstdio>
using namespace std;
int gcd(long a,long b){
==>最大公约数if(b==0) return a;return gcd(b,a%b);
}
==>根据题目要求格式化表达式的组成部分
void func(long long a,long long b){
if(a*b==0){
==>特判该部分为零的情况printf("%s",b==0?"Inf":"0");return;}bool flag=(a>0&&b<0||a<0&&b>0); ==>flag==true表示该部分为负数a=abs(a); b=abs(b);if(flag==true){
==>如果为负数printf("(-");}long long zheng=a/b; ==>整数部分long long temp; ==>储存gcd的值if(a%b==0){
==>如果该部分为整数if(flag==true) printf("%lld)",zheng);else printf("%lld",zheng);}else{
if(zheng!=0) printf("%lld ",zheng); ==>整数部分不为0就输出a%=b; ==>开始化简带分数的分数部分temp=gcd(a,b);if(flag==true) printf("%lld/%lld)",a/temp,b/temp);else printf("%lld/%lld",a/temp,b/temp);}
}
int main(){
long long a,b,c,d;scanf("%lld/%lld %lld/%lld",&a,&b,&c,&d); ==>scanf格式化输入,妙啊!==>下面按照四则运算法则输出即可func(a,b);printf(" + ");func(c,d);printf(" = ");func(a*d+c*b,b*d);printf("\n");func(a,b);printf(" - ");func(c,d);printf(" = ");func(a*d-c*b,b*d);printf("\n");func(a,b);printf(" * ");func(c,d);printf(" = ");func(a*c,b*d);printf("\n");func(a,b);printf(" / ");func(c,d);printf(" = ");func(a*d,b*c);printf("\n");return 0;
}