C++版浙大PAT乙级1034(20分)测试点2答案错误解决办法

https://pintia.cn/problem-sets/994805260223102976/problems/994805287624491008

测试点3是要改 int 为 long long 类型。测试点2一直都无法通过,百度了好多次都没找到解决方法。

最终看到这个链接的内容,发现是正负号的问题,因为一开始我的 sign 是靠 a*b 的积来判断的,不知道为什么会出错,可能是编译器的问题。

https://zhuanlan.zhihu.com/p/79893504

还有最大公约数的求法,是欧几里德算法,也叫辗转相除法。 

#include<iostream>
#include<math.h>
#include<string.h>
using namespace std;

// 最大公约数
long long gcd(long long a,long long b){
	long long t=0;
	while(b!=0){
		t=a%b;
		a=b;
		b=t;
	}
	return a;
}
// 递归版
// int gcd(int a,int b){
//     return b==0 ? a : gcd(b, a%b);
// } 

string simplfy(long long a, long long b){
	string str;
	// 如果分母or分子为0
	if(b == 0) return "Inf";
	if(a == 0) return "0";
    // 下面的写法无法通过测试点2
	// int sign = a*b<0 ? -1 : 1;
    // 如果分子or分母为负
    int sign = 1;
    if(a<0)
        sign *= -1;
    if(b<0)
        sign *= -1;
	a = abs(a);
	b = abs(b);
	// 找最大公约数进行约分
	long long divisor = gcd(a, b);
	a = a / divisor;
	b = b / divisor;
	// 有整数部分
	if(a/b!=0){
		str += to_string(a/b);
		if(a%b!=0)// 没被整除
			str += " " + to_string(a%b) + "/" + to_string(b);
	}else// 没整数部分
		str += to_string(a) + "/" + to_string(b);
	// 如果是负数
	if(sign<0)
		str = "(-"+str+")";
	return str;
}

int main() {
	long long a1, b1, a2, b2;
	string str1, str2, res;
	scanf("%lld/%lld %lld/%lld", &a1, &b1, &a2, &b2);
	str1 = simplfy(a1, b1);
	str2 = simplfy(a2, b2);
	// 加
	res = simplfy(a1*b2+a2*b1, b1*b2);
	cout << str1 << " + " << str2 << " = " << res << endl;
	// 减
	res = simplfy(a1*b2-a2*b1, b1*b2);
	cout << str1 << " - " << str2 << " = " << res << endl;
	// 乘
	res = simplfy(a1*a2, b1*b2);
	cout << str1 << " * " << str2 << " = " << res << endl;
	// 除
	res = simplfy(a1*b2, b1*a2);
	cout << str1 << " / " << str2 << " = " << res << endl;
	return 0;
}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值