编辑!!:
我忘记添加这个,它出现在我的代码中:
from math import sin, cos, tan, asin, acos, atan2, radians, degrees, sqrt
我正在计算净力,我遇到了一个路障。我对这个问题的反馈似乎是,我需要:
“在使用for循环中的cos/sin操作弧度之前,先将其转换为弧度。”
我已经为此工作了好几个小时,我不得不说我的大脑有点紧张。有人能帮我吗
这应该打印出来:
(87.0,54.4)
现在我得到的只是一个错误:
UnboundLocalError:赋值前引用的局部变量“horiztonal_total”
这是我的密码:
def find_net_force(forces):
horizontal_total = 0
vertical_total = 0
for i in forces:
horizontal = i[0] * cos(i[1])
vertical = i[0] * sin(i[1])
horiztonal_total += horizontal
vertical_total += vertical
total_magnitude = sqrt(horizontal_total ** 2 + vertical_total ** 2)
horiztonal_total = radians(horizontal_total)
vertical_total = radians(vertical_total)
total_angle = atan2(vertical_total, horizontal_total)
total_angle = degrees(total_angle)
total_magnitude = round(total_magnitude, 1)
total_angle = round(total_angle, 1)
force = (total_magnitude, total_angle)
return force
forces = [(10, 90), (10, -90), (100, 45), (20, 180)]
print(find_net_force(forces))
您的输入以度为单位,正弦波和余弦以弧度为单位。所以你需要写:
这两条线没有意义:
总而言之
输出
使用@CryptoFool的注释:
你做得很好,我所做的唯一改变就是在两个不同的地方更正从
horiztonal_total
到horizontal_total
的拼写错误,导入相关的数学函数,然后从度转换为弧度,因为在math
中,这些函数以弧度为参数,角度以度为单位您的代码有许多问题。从语法上讲,有两种:
horiztonal_total
是一个打字错误。在所有情况下都应为horizontal_total
您需要导入数学函数:
从逻辑上讲,问题是当您应用
radians()
时。你在错误的地方做,而不是在你应该做的地方做。以下是给出正确答案的代码版本:结果
记住
radians()
将度转换为弧度。还要知道,所有数学运算都接受以弧度表示的角度和返回角度。因为您的输入值是以度为单位的,所以在将它们传递给sin()
或cos()
之前,将它们的引用包装在radians()
中是有意义的,如cos(radians(i[1]))
。这给了你一个单位力。也就是说,假设总力为1
,则为特定方向上的力。要从1
以外的某个量级获得总力,可以将该量级乘以sin/cos的返回值,您已经在这样做了atan2
实际上与调用sin()
和cos()
相反。它把一对震级变成一个角度。结果以弧度为单位。由于您希望以度为单位的结果与输入值匹配,因此可以对结果调用degrees
干得好。你真的很接近!快乐编码
相关问题 更多 >
编程相关推荐