在Python中除以零错误?

时间:2014-02-06 03:55:55

标签: python syntax-error

我正在编写一个程序,用户输入a,b,c,d,e和f并显示结果。如果ad - bc = 0,我应该报告没有解决方案。但即使我将代码的一部分包含在:

if denominator == 0: print("The equation has no solution")

我一直得到零除错误。我用于提示的数字分别是1.0,2.0,2.0,4.0,4.0,5.0。这是我的代码:

def cramersRule():

a = float(input("Enter a: "))
b = float(input("Enter b: "))
c = float(input("Enter c: "))
d = float(input("Enter d: "))
e = float(input("Enter e: "))
f = float(input("Enter f: "))

denominator = ((a * d) - (b * c))

x = (((e * d) - (b * f)) / denominator)
y = (((a * f) - (e * c)) / denominator)
e = ((a * x) + (b * y)) 
f = ((c * x) + (d * y))
if denominator == 0:
    print("The equation has no solution.")
else:
    print("x is", x , "and y is" , y)

请帮忙!

4 个答案:

答案 0 :(得分:2)

您正在使用它执行计算:

x = (((e * d) - (b * f)) / denominator)
y = (((a * f) - (e * c)) / denominator)

这就是你得到错误的原因。您必须首先检查分母是否为零。

def cramersRule():

    a = float(input("Enter a: "))
    b = float(input("Enter b: "))
    c = float(input("Enter c: "))
    d = float(input("Enter d: "))
    e = float(input("Enter e: "))
    f = float(input("Enter f: "))

    denominator = ((a * d) - (b * c))

    if denominator == 0:
        print("The equation has no solution.")
    else:
        x = (((e * d) - (b * f)) / denominator)
        y = (((a * f) - (e * c)) / denominator)
        e = ((a * x) + (b * y)) 
        f = ((c * x) + (d * y))
        print("x is", x , "and y is" , y)

答案 1 :(得分:2)

其他人都解决了你所问的问题;这是你没有问过的问题,更好的代码组织!

from __future__ import division       # all division is floating-point
import sys

# version compatibility
if sys.hexversion < 0x3000000:
    inp = raw_input                   # Python 2.x
else:
    inp = input                       # Python 3.x

def get_float(prompt):
    while True:
        try:
            return float(inp(prompt))
        except ValueError:
            pass

def cramers_rule(a, b, c, d, e, f):
    denominator = a*d - b*c
    if denominator:
        x = (e*d - b*f) / denominator
        y = (a*f - e*c) / denominator
        e = a*x + b*y
        f = c*x + d*y
        return x, y, e, f
    else:
        return None  # no solution

def main():
    prompt = "Enter {0}: ".format
    kwargs = {ch:get_float(prompt(ch)) for ch in 'abcdef'}
    res    = cramers_rule(**kwargs)

    if res is None:
        print("The equation has no solution.")
    else:
        print("x is {0} and y is {1}".format(*res))

if __name__=="__main__":
    main()

  1. 每个函数应该只做一件事:cramers_rule()应该计算Cramer的规则,它不应该做输入和输出。让cramers_rule()接受参数并返回结果意味着它可以被重用(即在实际计算中)。

  2. 错误检查输入 - 如果它没有崩溃,如果当你向用户询问浮动时,他们输入'马铃薯'(你知道某人会),这很好。委派给它所属的get_float()

  3. if x == 0:是unPythonic; PEP-8说if not x:是首选,因为它允许鸭子打字 - 该功能现在适用于任何知道如何进行基本操作的类型。我不知道将Cramer定律应用于张量是否合理,但如果确实如此,现在就可以了。

  4. Python操作符遵守操作顺序;我摆脱了一堆无关紧要的括号。

  5. 希望有所帮助; - )

答案 2 :(得分:1)

您应该使用try-except错误处理模式。这是一个基本的例子:

try:
    x = (((e * d) - (b * f)) / denominator)
except ZeroDivisionError:
   print("The equation has no solution.")
else:
   print("Success!")

答案 3 :(得分:1)

将您的支票零移至您之前的函数中,如下所示:

...
denominator = ((a * d) - (b * c)

if denominator == 0:
    print("The equation has no solution.")
else:
    x = (((e * d) - (b * f)) / denominator)
    y = (((a * f) - (e * c)) / denominator)
    e = ((a * x) + (b * y)) 
    f = ((c * x) + (d * y))
    print("x is", x , "and y is" , y)