本文主要是介绍pat 34 乙级 有理数四则运算最后两个测试点 不仅longlong坑你一把 也可能是abs绝对值,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
#include<stdio.h>
#include<math.h>long long int gcd(long long a, long long b) //求最大公约数
{if (a%b == 0) return b;else return gcd(b, a%b);
}
void huajian(long long *a, long long *b)
{long long t = abs(gcd(*a, *b));*a = *a / t;*b = *b / t;
}
void relation(long long int div, long long int Div)
{long long int k, kk;if (Div == 0) printf("Inf"); //除数等于0else if (div == 0)printf("%lld", div); //被除数等于0else if (div > 0) //被除数大于0{huajian(&div, &Div);if (div < Div) //真分数{ printf("%lld/%lld", div, Div); //输出}else { //假分数k = div / Div; //整数部分kk = div%Div;if (kk== 0) //整除printf("%lld", k);else //非整除{ //分子 //化简printf("%lld %lld/%lld", k, kk, Div);}}}else //被除数小于0{huajian(&div, &Div);if ((-1*div) < Div) //真分数{printf("(%lld/%lld)", div, Div);}else //假分数{k = div / Div; //整数部分kk = (-1*div)%Div;if (kk == 0) printf("(%lld)", k); //整除 else{printf("(%lld %lld/%lld)", k, kk, Div);}}}
}
void add_min_mul_div(long long int a, long long int b, char sign, long long int c, long long int d)
{relation(a, b);printf(" %c ", sign);relation(c, d);long long int a1, a2;switch (sign){case '+': a1 = a*d + b*c; a2 = b*d; break;case '-': a1 = a*d - b*c; a2 = b*d; break;case '*': a1 = a*c; a2 = b*d; break;case '/': a1 = a*d; a2 = b*c; if (a2 < 0) { a1 = -a1; a2 = -a2; }break; //保证分母大于0}printf(" = ");relation(a1, a2);
}
int main()
{char sign[] = { '+','-','*','/' };long long a, b, c, d;scanf("%lld/%lld %lld/%lld", &a, &b, &c, &d);for (int i = 0; i < 4; i++){add_min_mul_div(a, b, sign[i], c, d); printf("\n");}//while (1);return 0;
}
1.最后两个测试点花了大概五个小时。刚开始按照网上 的都改成longlong了 一直不过。最后 发现我之前代码乘-1部分用的绝对值。abs().abs参数是int型的 唉。。欲哭无泪
这篇关于pat 34 乙级 有理数四则运算最后两个测试点 不仅longlong坑你一把 也可能是abs绝对值的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!