将函数值返回为 float Python 3.6.1
Returning function values as float Python 3.6.1
我收到以下错误,似乎无法弄清楚如何解决。按照逻辑,我调用 3 个函数和所有 3 个 return 值作为浮点数,然后我对存储的 returned 值执行一些数学运算并将其打印为浮点数。那么哪里出了问题呢?我为 A 面输入 4,为 B 面输入 5。
错误信息:
输入A边的长度:4.0
输入B边的长度:5.0
Traceback (most recent call last):
File "python", line 26, in <module>
File "python", line 9, in main
File "python", line 24, in calculateHypotenuse
TypeError: unsupported operand type(s) for ^: 'float' and 'float'
import math
def main():
#Call get length functions to get lengths.
lengthAce = getLengthA()
lengthBee = getLengthB()
#Calculate the length of the hypotenuse
lengthHypotenuse = calculateHypotenuse(float(lengthAce),float(lengthBee))
#Display length of C (hypotenuse)
print()
print("The length of side C 'the hypotenuse' is {}".format(lengthHypotenuse))
#The getLengthA function prompts for and returns length of side A
def getLengthA():
return float(input("Enter the length of side A: "))
#The getLengthA function prompts for and returns length of side B
def getLengthB():
return float(input("Enter the length of side B: "))
def calculateHypotenuse(a,b):
return math.sqrt(a^2 + b^2)
main()
print()
print('End of program!')
^
in Python 是 bitwise XOR operator,不是幂运算符:
The ^ operator yields the bitwise XOR (exclusive OR) of its arguments, which must be intege
您需要改用 **
, 是 幂运算符:
def calculateHypotenuse(a,b):
return math.sqrt(a**2 + b**2)
我收到以下错误,似乎无法弄清楚如何解决。按照逻辑,我调用 3 个函数和所有 3 个 return 值作为浮点数,然后我对存储的 returned 值执行一些数学运算并将其打印为浮点数。那么哪里出了问题呢?我为 A 面输入 4,为 B 面输入 5。
错误信息:
输入A边的长度:4.0 输入B边的长度:5.0
Traceback (most recent call last):
File "python", line 26, in <module>
File "python", line 9, in main
File "python", line 24, in calculateHypotenuse
TypeError: unsupported operand type(s) for ^: 'float' and 'float'
import math
def main():
#Call get length functions to get lengths.
lengthAce = getLengthA()
lengthBee = getLengthB()
#Calculate the length of the hypotenuse
lengthHypotenuse = calculateHypotenuse(float(lengthAce),float(lengthBee))
#Display length of C (hypotenuse)
print()
print("The length of side C 'the hypotenuse' is {}".format(lengthHypotenuse))
#The getLengthA function prompts for and returns length of side A
def getLengthA():
return float(input("Enter the length of side A: "))
#The getLengthA function prompts for and returns length of side B
def getLengthB():
return float(input("Enter the length of side B: "))
def calculateHypotenuse(a,b):
return math.sqrt(a^2 + b^2)
main()
print()
print('End of program!')
^
in Python 是 bitwise XOR operator,不是幂运算符:
The ^ operator yields the bitwise XOR (exclusive OR) of its arguments, which must be intege
您需要改用 **
, 是 幂运算符:
def calculateHypotenuse(a,b):
return math.sqrt(a**2 + b**2)