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

[python]分数运算及表达式输出,第1张

读入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])

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/799425.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-06
下一篇 2022-05-06

发表评论

登录后才能评论

评论列表(0条)

保存