尝试编写一段计算直线斜率的代码,正在使用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)每当输入使答案不合理的数字时,答案就会变成十进制。是否可以将其保留为零呢?
解决:
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