zoukankan      html  css  js  c++  java
  • A1088 Rational Arithmetic [分数四则运算]

    在这里插入图片描述

    #include<cstdio>
    #include<iostream>
    #include<algorithm>
    using namespace std;
    typedef long long ll;
    ll gcd(ll a, ll b)
    {
    	if (b == 0)
    		return a;
    	else
    		return gcd(b, a % b);
    }
    struct fraction
    {
    	ll up, down;
    }f1,f2;
    fraction simplify(fraction result)
    {
    	if (result.down < 0)
    	{
    		result.up = -result.up;
    		result.down = -result.down;
    	}
    	int d = gcd(abs(result.up), abs(result.down));
    	result.up /= d;
    	result.down /= d;
    	return result;
    }
    fraction add(fraction a, fraction b)
    {
    	fraction result;
    	result.up = a.up * b.down + b.up * a.down;
    	result.down = a.down * b.down;
    	return simplify(result);
    }
    fraction Minus(fraction a, fraction b)
    {
    	fraction result;
    	result.up = a.up * b.down - b.up * a.down;
    	result.down = a.down * b.down;
    	return simplify(result);
    }
    fraction mul(fraction a, fraction b)
    {
    	fraction result;
    	result.up = a.up * b.up;
    	result.down = a.down * b.down;
    	return simplify(result);
    }
    fraction divide(fraction a, fraction b)
    {
    	fraction result;
    	result.up = a.up * b.down;
    	result.down = a.down * b.up;
    	return simplify(result);
    }
    void showresult(fraction r)
    {
    	r = simplify(r);
    	if (r.up < 0)
    		cout << "(";
    	if (r.down == 1)
    		cout << r.up;
    	else if (abs(r.up) > abs(r.down))
    	{
    		printf("%lld %lld/%lld", r.up / r.down, abs(r.up) % r.down, r.down);
    	}
    	else
    	{
    		printf("%lld/%lld", r.up, r.down);
    	}
    	if (r.up < 0)
    		cout << ")";
    }
    int main()
    {
    	scanf("%lld/%lld %lld/%lld", &f1.up, &f1.down, &f2.up, &f2.down);
    	showresult(f1);
    	printf(" + ");
    	showresult(f2);
    	cout << " = ";
    	showresult(add(f1, f2));
    	cout << endl;
    	showresult(f1);
    	printf(" - ");
    	showresult(f2);
    	cout << " = ";
    	showresult(Minus(f1, f2));
    	cout << endl;
    	showresult(f1);
    	printf(" * ");
    	showresult(f2);
    	cout << " = ";
    	showresult(mul(f1, f2));
    	cout << endl;
    	showresult(f1);
    	printf(" / ");
    	showresult(f2);
    	cout << " = ";
    	if (f2.up == 0)
    		cout << "Inf";
    	else
    		showresult(divide(f1, f2));
    	return 0;
    }
    
  • 相关阅读:
    流畅的python——2 数据结构
    流畅的python——1 数据模型
    cpp3 std::bind
    cpp2 std::forward
    什么是 jQuery EasyUI?
    .Core中什么事依赖注入?
    .net 中datetime? 和 datetime 有什么区别?
    C#生成项目失败 错误列表 CS2001 未能找到源文件 “D:XXXXXX.cs”。
    Docker笔记
    ICollection与IEnumerable
  • 原文地址:https://www.cnblogs.com/Hsiung123/p/13812047.html
Copyright © 2011-2022 走看看