gpt4 book ai didi

Python - 输出分数而不是小数

转载 作者:行者123 更新时间:2023-12-02 03:18:42 25 4
gpt4 key购买 nike

所以我试图编写一段代码来计算直线的斜率。我用的是3.6。

    y1 = float(input("First y point: "))
y2 = float(input("Second y point: "))
x1 = float(input("First X point: "))
x2 = float(input("Second X point: "))

slope = (y2 - y1)/(x2 - x1)

print("The slope is:",slope)

每当我输入使答案变得无理数的数字时,答案就会变成小数。是否可以将其保留为分数?

最佳答案

是的,请参阅https://docs.python.org/3.6/library/fractions.html (但在这种情况下分子和分母应该是有理数,例如整数):

from fractions import Fraction

y1 = int(input("First y point: "))
y2 = int(input("Second y point: "))
x1 = int(input("First X point: "))
x2 = int(input("Second X point: "))

slope = Fraction(y2 - y1, x2 - x1)

print("The slope is:", slope, "=", float(slope))

输入和输出:

First y point: 5
Second y point: 7
First X point: 10
Second X point: 15
The slope is: 2/5 = 0.4

关于Python - 输出分数而不是小数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42180507/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com