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;
    }
    
  • 相关阅读:
    实验17:NAT
    实验16:ACL
    实验15: STP
    实验14:VLAN间的路由
    实验13:VLAN/TRUNK/VTP/
    Linux软件管理--RPM工具
    Linux拓展练习部分--输入输出 / find部分 /基础拓展2
    linux文件管理--压缩打包
    find 文件查找
    防火墙知识点
  • 原文地址:https://www.cnblogs.com/Hsiung123/p/13812047.html
Copyright © 2011-2022 走看看