当我在代码中使用(0)作为num1方程时崩溃python

import cmath
import math


print(" we are going to programming second grade equation in python")
print(" a^2 x + b x + c =0")

num1 = int(input(" enter A please : "))
num2 = int(input(" enter B please : "))
num3 = int(input(" enter c please : "))

v = num2*num2 - 4 *num1 * num3

if v < 0:
    print("wrong values")

else:
    print("root of delta =",v)
    k= math.sqrt(v)

def two_sol(x,y) :
    x_f= (-y + v)/(4*x)
    x_s =(-y - v)/(4*x)

    return x_f,x_s

def one_sol(x):
    x_f = (-y + v) / (4 * x)

if v >0 :
    print("we have two solution :",two_sol(num1,num2)) 

elif v == 0:
   print( "we have one solution :",one_sol(y))

else:
    print(" there is no solution !!")
wkz123456 回答:当我在代码中使用(0)作为num1方程时崩溃python

当然,您有一个被零除的错误:num1-> x

def two_sol(x,y) :
    x_f= (-y + v)/(4*x)
    x_s =(-y - v)/(4*x)

def one_sol(x):
    x_f = (-y + v) / (4 * x)

您需要检查x是否为零。如果x为零,则应该只有一个解。

希望有帮助。

,

之所以发生这种情况,是因为我们无法将任何数字除以0,所以您不想做什么? 如果需要,当x输入为0时将其替换为1,表示数字除以1,则代码为

def two_sol(x,y) :
    if int(x) == 0: x = 1 
    x_f= (-y + v)/(4*x)
    x_s =(-y - v)/(4*x)

    return x_f,x_s

def one_sol(x):
     if int(x) == 0: x = 1 
     x_f = (-y + v) / (4 * x)

否则,如果x输入为0,则返回并且不再计算!代码将是

    def two_sol(x,y) :
    if int(x) == 0: return 
    x_f= (-y + v)/(4*x)
    x_s =(-y - v)/(4*x)

    return x_f,x_s

def one_sol(x):
     if int(x) == 0: return 
     x_f = (-y + v) / (4 * x)
本文链接:https://www.f2er.com/3148624.html

大家都在问