栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

[python]分数运算及表达式输出

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

[python]分数运算及表达式输出

读入4个整数a、b、c、d和一个运算符(‘+’、‘-’、‘*’、‘/’中的一个),进行分数a/b和c/d的对应运算,输出最简结果。

Standard Input

有多组测试数据。输入的第一行是整数T(1<=T<=200),表示随后测试数据的组数。每组测试数据占一行,由四个正整数a,b,c,d和一个运算符组成,相邻数据间有一个空格。

Standard Output

对应每组测试数据,输出分数运算的最简结果,占一行。具体可参照样例。

Samples
InputOutput
3
1 2 3 4 -
35 24 24 5 *
25 72 9 5 /
1/2-3/4=-1/4
35/24*24/5=7
25/72/9/5=125/648
Problem ID1891
Problem Title分数运算
Time Limit1000 ms
Memory Limit64 MiB
Output Limit64 MiB
Sourcewxiaoping - 2018.4.16

用python写很简单,所以没有思考C语言的方法。。。

实现代码如下:

from fractions import Fraction

T = int(input())
fun = []
for x in range(T):
    a1, b1, a2, b2, s = map(str, input().split())
    a = Fraction(int(a1), int(b1))
    b = Fraction(int(a2), int(b2))

    if (s == "+"):
        res = a + b
    elif (s == '-'):
        res = a - b
    elif (s == '*'):
        res = a * b
    elif (s == '/'):
        res = Fraction(a, b)
    biao = str(a1)+'/'+str(b1)+s+str(a2)+'/'+str(b2)+'='+str(res)
    fun.append(biao)
for x in range(T):
    print(fun[x])

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/859391.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号