Python程序,它告诉你一条线的斜率

时间:2014-09-21 03:00:15

标签: python variables

所以我是python的新手,但是已经成功创建了可以计算面积,体积,将摄氏温度转换为华氏温度等的程序...但是,我似乎遇到了一些问题,这个'斜率为& #39;程序

# A simple program which prompts the user for two points 
# and then computes and prints the corresponding slope of a line.

# slope(S): (R*R)*(R*R) -> R
# If R*R is a pair of real numbers corresponding to a point,
# then slope(S) is the slope of a line.
def x1(A):
    def y1(B):
        def x2(C):
            def y2(D):
                def slope(S):
                    return (D-B)/(C-A)

# main
# Prompts the user for a pair of points, and then computes
# and prints the corresponding slope of the line.

def main():
    A = eval(input("Enter the value of x1:"))
    B = eval(input("Enter the value of y1:"))
    C = eval(input("Enter the value of x2:"))
    D = eval(input("Enter the value of y2:"))
    S = slope(S)
    print("The slope of a line created with those points\
 is: {}{:.2f}".format(S,A,B,C,D))

main()

2 个答案:

答案 0 :(得分:6)

斜率函数可能类似于以下内容 - 一个函数采用四个参数来表示这两个点的四个坐标:

def slope(x1, y1, x2, y2):
    return (y1 - y2) / (x1 - x2)

但显然不应该这么简单,你必须改进它并考虑x1 == x2的情况。

答案 1 :(得分:0)

斜率=上升/下降。这是一个非常简单的解决方案: - 使用x和y成员创建一个Point类。 - 创建一个方法getSlope,它将两个点作为参数 - 使用x和y坐标实例化两个点变量。 - 打印结果(在这种情况下是getSlope方法的返回值。

class Point:
    def __init__ (self, x, y):
        self.x = x
        self.y = y

# This could be simplified; more verbose for readability    
def getSlope(pointA, pointB):
    rise = float(pointA.y) - float(pointB.y)
    run = float(pointA.x) - float(pointB.x)
    slope = rise/run

    return slope


def main():
    p1 = Point(4.0, 2.0)
    p2 = Point(12.0, 14.0)

    print getSlope(p1, p2)

    return 0

if __name__ == '__main__':
    main()