如何更改函数或避免错误

wpx232ag  于 2021-09-08  发布在  Java
关注(0)|答案(2)|浏览(420)

我不知道我是否写错了“line”函数,或者在“for”之后的最后语句中是否有其他内容,请帮助我。这个程序是关于斜率和比较这些值,但首先我需要找到它们,但有些东西不起作用。代码是下一个:

import math

N = int(input("Number of points: "))

def line(x0,y0,x1,y1):
  if(x0==x1):
    print("\nThe slope doesn't exist\n")
    return None
  if((x0-x1)!=0):
    m = (y1-y0)/(x1-x0)
    return m

for i in range(N):
  for j in range(N):
    ind = None
    for ind in range(N):
      x_ind = {}
      y_ind = {}
      x_ind[i] = float(input("Enter x_" + str(ind) + ": "))
      y_ind[j] = float(input("Enter y_" + str(ind) + ": "))
    for _ in range(math.factorial(N-1)):
      line(x_ind[i], y_ind[j], x_ind[i+1], y_ind[j+1])
sq1bmfud

sq1bmfud1#

tl;dr-您在for循环中声明了您的字典,因此它们在每次新的迭代中都会被重置。
我想你是想这么做-

N = int(input("Number of points: "))

def line(x0,y0,x1,y1):
  # calculate slope for (x0,y0) and (x1,y1)
  if x0 == x1:            # it will be a vertical line, it has 'undefined' slope
    # print("The slope doesn't exist\n")
    return 'Undefined'
  else:                   # this is implied, no need to put extra check --> x0-x1 != 0:
    return (y1-y0)/(x1-x0)
  pass

# declare variables

x_ind = {}
y_ind = {}
for i in range(N):
  # read inputs and update the existing variables
  x_ind[i] = float(input("Enter x_" + str(i) + ": "))
  y_ind[i] = float(input("Enter y_" + str(i) + ": "))
  print(x_ind, '\n', y_ind)

# calculate slope for every pair of points

for j in range(N):
  for k in range(j+1,N):
    m = line(x_ind[j], y_ind[j], x_ind[k], y_ind[k])
    print(f'slope of line made using points: ({x_ind[j]}, {y_ind[j]}) and ({x_ind[k]}, {y_ind[k]}) is {m}')
vxqlmq5t

vxqlmq5t2#

尝试使用列表而不是字典,以便正确使用索引值:

x_ind = []
y_ind = []

由于列表为空,您可以使用 append() 方法将元素推送到列表中,正如我所看到的,这就是您打算做的。

相关问题