问题描述
''' 当我运行测试用例时,我的程序中有一小部分给我带来了问题。我有一个检查以确保用户输入三个值。如果用户没有输入三个值,它会显示一条消息,然后再次调用该函数。如果用户第一次输入三个值,它会进行并打印计算并继续。这是它变得不稳定的地方,如果用户没有输入三个值,它会再次提示用户,直到他们输入三个值,然后它进行并打印计算,然后给我索引错误。我在那里有一个打印语句来检查输入列表,那里有三个值......我完全不知道为什么我在第二遍而不是第一遍得到错误。 '''
def cos_angle():
get_data = input("Please enter the kNown two sides and the angle\n" +
"across from the unkNown side.\n" +
"(Entries should be separated by a space) ").split()
if len(get_data) != 3:
print("\nIncorrect number of entries. You should input three numbers.\n")
cos_angle()
side_a = int(get_data[0])
side_b = int(get_data[1])
angle = int(get_data[2])
print(get_data)
c = sqrt((side_a**2 + side_b**2) - 2*side_a*side_b*cos(rad(angle)))
print("\nThe value of the missing side of the triangle is {:.4f}.\n".format(c))
cos_angle()
解决方法
有多个具有不同值的 get_data
变量。
使用循环,而不是递归。
def cos_angle():
get_data = input("Please enter the known two sides and the angle\n" +
"across from the unknown side.\n" +
"(Entries should be separated by a space) ").split()
while len(get_data) != 3:
print("\nIncorrect number of entries. You should input three numbers.\n")
get_data = input("Please enter the known two sides and the angle\n" +
"across from the unknown side.\n" +
"(Entries should be separated by a space) ").split()
side_a = int(get_data[0])
side_b = int(get_data[1])
angle = int(get_data[2])
print(get_data)
c = sqrt((side_a**2 + side_b**2) - 2*side_a*side_b*cos(rad(angle)))
print("\nThe value of the missing side of the triangle is {:.4f}.\n".format(c))
cos_angle()