这个程序是为了找到矢量的标准化,但是我无法打印列表:
Def功能:
def _unit_vector_sample_(vector):
# calculate the magnitude
x = vector[0]
y = vector[1]
z = vector[2]
mag = ((x**2) + (y**2) + (z**2))**(1/2)
# normalize the vector by dividing each component with the magnitude
new_x = x/mag
new_y = y/mag
new_z = z/mag
unit_vector = [new_x, new_y, new_z]
#return unit_vector
主程序:
vector=[2,3,-4]
def _unit_vector_sample_(vector):
print(unit_vector)
如何纠正错误?
答案 0 :(得分:0)
试试这个:
def _unit_vector_sample_(vector):
# calculate the magnitude
x = vector[0]
y = vector[1]
z = vector[2]
mag = ((x**2) + (y**2) + (z**2))**(1/2)
# normalize the vector by dividing each component with the magnitude
new_x = x/mag
new_y = y/mag
new_z = z/mag
unit_vector = [new_x, new_y, new_z]
return unit_vector
vector=[2,3,-4]
print(_unit_vector_sample_(vector))
打印此输出:
[0.3713906763541037, 0.5570860145311556, -0.7427813527082074]
您需要在your _unit_vector_sample
函数中声明一个return语句。否则你的函数会运行,但它无法将结果返回给main。
或者你可以这样做:
def _unit_vector_sample_(vector):
# calculate the magnitude
x = vector[0]
y = vector[1]
z = vector[2]
mag = ((x**2) + (y**2) + (z**2))**(1/2)
# normalize the vector by dividing each component with the magnitude
new_x = x/mag
new_y = y/mag
new_z = z/mag
unit_vector = [new_x, new_y, new_z]
print(unit_vector)
vector=[2,3,-4]
_unit_vector_sample_(vector)
导致打印相同的输出:
[0.3713906763541037, 0.5570860145311556, -0.7427813527082074]
这里通过在函数中调用print,每次运行函数时都会打印unit_vector。
使用哪一个取决于您想要做什么。 您是否还希望将函数的结果分配给main中的变量,然后使用第一个解决方案(而不是直接打印函数的结果将其分配给变量)。如果不需要,您可以使用第二个选项。