我正在尝试编写一个程序,用户可以输入两个值,程序将计算值之间的绝对误差。
示例输入为:
87.03
87
首先读取近似值,然后读取正确的值。输出应为:
The absolute error is: 0.03
这是我拒绝工作的尝试!
a=raw_input("What is the approximate value?")
b=raw_input("What is the correct value?")
print "The absolute error is: %s" %abs(a-b)
我得到的错误是:
TypeError
Traceback (most recent call last)
<ipython-input-1-9320453c4e23> in <module>()
1 a=raw_input("What is the approximate value?")
2 b=raw_input("What is the correct value?")
----> 3 print "The absolute error is: %s" %abs(a-b)
TypeError: unsupported operand type(s) for -: 'str' and 'str'
我真的不知道这意味着什么。任何帮助将不胜感激。
答案 0 :(得分:1)
a = float(raw_input("What is the approximate value?"))
b = float(raw_input("What is the correct value?"))
您需要输入floats
raw_input("What is the approximate value?")
是一个字符串。
In [8]: b = "0.85"
In [9]: a = "10.5"
In [10]: a-b
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-10-12776d70544b> in <module>()
----> 1 a-b
TypeError: unsupported operand type(s) for -: 'str' and 'str'
In [11]: a = float("10.5")
In [12]: b = float("0.85")
In [13]: a-b
Out[13]: 9.65
答案 1 :(得分:1)
raw_input
将从用户获取输入字符串并将其保留为字符串。因此,当a-b
和a
都是字符串时,您正在尝试b
。首先使用float
将其转换为float()
。
a = float(raw_input("What is the approximate value?"))
b = float(raw_input("What is the correct value?"))