猫史档案馆


【Python作品分享】分数

用户:张智皓123张智皓123查看:0 回复:1 评论:0 创建时间:2021-11-20T13:27:47


【作品展示】

center_image

 

【作品介绍】

也不说废话,直接切入正题:

这是一个功能库,加入了分数类型,各位大佬可以在这基础上制作分数计算器等。

这个库中新添了Fenshu的数据类型,有mother分母和son分子。这个类型自带3个方法:printf()打印(如3 / 4)、yuefen()约分和chengfang(num)乘方(num指数)

此外,这个库还带有4个加(add)减(subtract)乘(multiply)除(devide),都要两个Fenshu类型的数据对象作为参数。

创作不易,希望给个点赞吧!O(∩_∩)O

(注:强烈推荐小编另一作品电魂;导入库函数方法见评论区)

 

【作品源代码】

class Fenshu():
    def __init__(self,mother,son):
        self.mother=mother
        self.son=son
    
    def printf(self):
        print(self.son,'/',self.mother)

    def yuefen(self):
        m=min(abs(self.mother),abs(self.son))
        ans=0
        for i in range(1,m+1):
            if self.mother%i==0 and self.son%i==0:
                ans=i
        self.mother=int(self.mother/ans)
        self.son = int(self.son/ans)
        if self.son<0 and self.mother<0:
            self.som=0-self.son
            self.mother=0-self.mother
    
    def chengfang(self,num):
        self.mother=self.mother**num
        self.son=self.son**num

def add(f1,f2):
    ans=Fenshu(
        son=f1.mother*f2.son+f2.mother*f1.son,
        mother=f1.mother*f2.mother
    )
    ans.yuefen()
    return ans

def subtract(f1,f2):
    f2.mother=0-f2.mother
    ans=add(f1,f2)
    return ans

def multiply(f1,f2):
    mother=f1.mother*f2.mother
    son=f1.son*f2.son
    ans=Fenshu(mother=mother,son=son)
    ans.yuefen()
    return ans

def devide(f1,f2):
    mother=f2.son
    son=f2.mother
    f3=Fenshu(mother=mother,son=son)
    ans=multiply(f1,f3)
    return ans



 

【提示】

部分含有Python第三方库相关内容的作品,在海龟编辑器网页端无法运行哦!如遇到这种情况,可以打开下面的链接,下载海龟编辑器客户端:

https://python.codemao.cn


回复

上一页1 页 / 共 1下一页
张智皓123张智皓123

库函数导入方法:

1.复制代码;

2.打开海龟编辑器,复制代码并保存;

3.将需要使用该库的文件保存在库文件同一目录下;

4.在使用该库的代码开头写:from 分数 import *(海龟编辑器不加引号也可以写中文)

5.导入成功!

使用举例:

创建分数类型对象:f=Fenshu(mother=2,son=1)

使用加减乘除函数:add(f1,f2)

点赞0


评论