|
发表于 2017-11-15 13:55:33
|
显示全部楼层
加完了,还要求最大公约数:
- # -*- coding: utf-8 -*-
- """
- Created on Wed Nov 15 12:02:30 2017
- """
- def fracAdd(n1, d1, n2, d2):
- n3 = d1*n2 + d2*n1
- d3 = d1*d2
-
- c3 = commonDivisor2(n3, d3)
-
- return (int(n3/c3), int(d3/c3))
- def commonDivisor2(num1,num2):
- if num1==num2:return num1
- elif num1 < num2:
- temp = num1
- num1 = num2
- num2 = temp
- if num1 - num2 == num2:
- return num2
- else:
- temp = num1
- num1 = num2
- num2 = temp - num2
- #print (num1,' ', num2)
- return commonDivisor2(num1,num2)
- test = fracAdd(1, 6, 2, 3)
- print ('1 / 6 + 2 / 3 = ', test[0],'/',test[1])
- test = fracAdd(1, 4, 7, 8)
- print ('1 / 4 + 7 / 8 = ', test[0],'/',test[1])
- test = fracAdd(1, 6, 1, 3)
- print ('1 / 6 + 1 / 3 = ', test[0],'/',test[1])
复制代码
1 / 6 + 2 / 3 = 5 / 6
1 / 4 + 7 / 8 = 9 / 8
1 / 6 + 1 / 3 = 1 / 2 |
评分
-
查看全部评分
|