上一篇的代码没有完善,我改了一下,给你们看看:
equation = input("请输入一元一次方程,目前支持ax+b=0形式的方程:")
print("备注:本工具暂时仅支持ax+b=0的形式,其他形式可能报错或者计算错误。")
equation.strip()
true = 0
x = int(equation.index('x'))
equat = int(equation.index('='))
if equation.index('x') == 0:
a = 1
else:
a = float(equation[0 : x])
if equat - x == 1:
b = 0
else:
try:
b = float(equation[x + 1 : equat])
except ValueError:
b = 0
try:
conclusion = -(b / a)
except ZeroDivisionError:
a = 1e-323
conclusion = -(b / a)
try:
if int(conclusion) == conclusion:
conclusion = int(conclusion)
except OverflowError:
print("x=∞")
true = 1
pass
if true == 0:
print('x=' + str(conclusion))
备注:如上1e-323是Python能够计算的最小值,算出来趋向于0。1e-324则会等于零。