繁体   English   中英

使用 python 的二次公式

[英]quadratic formula using python

尝试创建一个程序,该程序接受三个 arguments 代表二次公式中的 a、b 和 c 值。 值应保留两位小数。 您不需要考虑虚值。 然后以以下形式打印出两个根:

The solutions are x and y

其中xy分别对应于正根和负根。

我的代码有问题:

import math

a = float(input('please input a number:'))
b = float(input('please input a number3:'))
c = float(input('please input a number2:'))
d = (b**2) - (4*a*c)

sol1 = str(round((-b-cmath.sqrt(d))/(2*a),2))
sol2 = str(round((-b+cmath.sqrt(d))/(2*a),2))

print('The solution are {1.real:.2f} and {0.real:.2f}'.format(sol1,sol2))

在您的代码中,您导入了数学但使用了 cmath。 但是,更简单的解决方案是不导入任何内容并使用内置电源 function。 此外,python 自己处理打印整数、浮点数和复数,因此您无需担心转换。

尝试这个:

# Get inputs
a = float(input("a: "))
b = float(input("b: "))
c = float(input("c: "))

# Calculate discriminant
discriminant = b**2 - 4*a*c

# Get solutions, x^0.5 = square root
x1 = (-b + discriminant**0.5) / (2*a)
x2 = (-b - discriminant**0.5) / (2*a)

# Output
print(f"Solutions: {x1} and {x2}")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM