【发布时间】:2015-10-14 17:43:58
【问题描述】:
我正在制作一个极其简单的计算器风格应用程序,其中使用 5 个参数调用控制函数。第一个是设置计算器模式的字符串,其他 4 个是正在使用的数字。我用字典来方便各种模式之间的切换。
但是,应用程序似乎正在使用数字检查所有功能,而不仅仅是我想要的功能。例如,如果我另外使用负数,我会在平方根函数中得到数学域错误(显然不能使用负数)。使用正常的正数没有问题。
感谢您提供有关此问题发生原因以及解决方法的任何帮助或信息。
这是我的原始代码:
import math
def control(a, x, y, z, k):
return {
'ADDITION': addition(x, y),
'SUBTRACTION': subtraction(x, y),
'MULTIPLICATION': multiplication(x, y),
'DIVISION': division(x, y),
'MOD': modulo(x, y),
'SECONDPOWER': secondPower(x),
'POWER': power(x, y),
'SECONDRADIX': secondRadix(x),
'MAGIC': magic(x, y, z, k)
}[a]
def addition(x, y):
return float(x) + float(y)
def subtraction(x, y):
return float(x) - float(y)
def multiplication(x, y):
return float(x) * float(y)
def division(x, y):
return float(x) / float(y)
def modulo(x, y):
return float(x) % float(y)
def secondPower(x):
return math.pow(float(x),2.0)
def power(x, y):
return math.pow(float(x),float(y))
def secondRadix(x):
return math.sqrt(float(x))
def magic(x, y, z, k):
l = float(x) + float(k)
m = float(y) + float(z)
return (l / m) + 1.0
a = input()
x = input()
y = input()
z = input()
k = input()
try:
control(a, x, y, z, k)
except ValueError:
print("This operation is not supported for given input parameters")
out = control(a, x, y, z, k)
print(out)
这是日志:
C:\<path>\Python\Python35-32\python.exe C:/<path>/calculator.py
ADDITION
-6.0
5
3
2
This operation is not supported for given input parameters
Traceback (most recent call last):
File "C:/<path>/calculator.py", line 67, in <module>
out = control(a, x, y, z, k)
File "C:/<path>/calculator.py", line 13, in control
'SECONDRADIX': secondRadix(x),
File "C:/<path>/calculator.py", line 47, in secondRadix
return math.sqrt(float(x))
ValueError: math domain error
Process finished with exit code 1
【问题讨论】:
-
所以在您的示例中,您是否除了输出为 -1.0,因为您提供了键“ADDITION”并且前两个数字是 -6.0 和 5,问题是您传入了负数作为输入,你不能取负数的平方,而且由于你的代码返回你创建的字典,它会运行每个定义的方法,即使你只返回一个项目的值。跨度>
标签: python function math dictionary switch-statement