绝对误差计算的代码
我正在尝试写一个程序,让用户可以输入两个数值,然后程序会计算这两个数值之间的绝对误差。
一个示例输入可能是:
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'
我真的不知道这是什么意思。任何帮助都会非常感谢。
2 个回答
1
a = float(raw_input("What is the approximate value?"))
b = float(raw_input("What is the correct value?"))
你需要把输入转换成 浮点数
。
raw_input("你觉得这个值大概是多少?")
如果不转换成浮点数的话,它得到的结果是一个字符串。
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
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?"))