如何解决如何格式化二次方程式输出?
程序中的所有内容都可以正常工作,除非打印出“解决方案是:” s1
和s2
的答案后面带有+0.00j
打印出来。如何将输出格式化为仅两位小数?如您所见,我尝试了,.2f
,但没有成功,我们将不胜感激。
import cmath
#converting inputs into floats to avoid ValueError
a = 0
while a == 0:
try:
a = float(input("Enter a value for a: "))
if a == 0:
raise ZeroDivisionError
except ZeroDivisionError:
print("The value you entered is invalid. Zero is not allowed")
except ValueError:
print("The value you entered is invalid. only real numbers")
else:
break
print()
while True:
try:
b = float(input("Enter a value for b: "))
except ValueError:
print("The value you entered is invalid. only real numbers")
else:
break
print()
while True:
try:
c = float(input("Enter a value for c: "))
except ValueError:
print("The value you entered is invalid. only real numbers")
else:
break
print()
#Calcualting discriminant,printing it and formatting it
disc = (b**2) - (4*a*c)
print("The discriminant is equal to: ",disc)
print()
#Calucating/printing solutions if there is one,two,or none
if disc < 0:
print ("No real solution")
elif disc == 0:
x = (-b+cmath.sqrt(disc))/(2*a)
print ("The solution is ",x)
else:
s1 = (-b+cmath.sqrt(disc))/(2*a)
s2 = (-b-cmath.sqrt(disc))/(2*a)
print ("The solutions are " + format(s1,",.2f"),"and " + format(s2,.2f"))
解决方法
只需打印出复数的.real
部分:
将相关行更改为
df %>%
mutate(check_column = case_when(!is.na(column2) & column1 %in%
c("Closed","pending") ~ "Check",TRUE ~ "Error"))
和
df %>%
mutate(check_column = case_when(column2 %in% "Closed"
~ "Check",TRUE ~ "Error"))
,
我修改了代码,看看效果是否更好:
bar
结果:
# import cmath
import math
#converting inputs into floats to avoid ValueError
a = 0
while a == 0:
try:
a = float(input("Enter a value for a: "))
if a == 0:
raise ZeroDivisionError
except ZeroDivisionError:
print("The value you entered is invalid. Zero is not allowed")
except ValueError:
print("The value you entered is invalid. only real numbers")
else:
break
print()
while True:
try:
b = float(input("Enter a value for b: "))
except ValueError:
print("The value you entered is invalid. only real numbers")
else:
break
print()
while True:
try:
c = float(input("Enter a value for c: "))
except ValueError:
print("The value you entered is invalid. only real numbers")
else:
break
print()
#Calcualting discriminant,printing it and formatting it
disc = (b**2) - (4*a*c)
print("The discriminant is equal to: ",disc)
print()
#Calucating/printing solutions if there is one,two,or none
if disc < 0:
print ("No real solution")
elif disc == 0:
# x = (-b+cmath.sqrt(disc))/(2*a)
x = -b/(2*a)
print ("The solution is ",x)
else:
#s1 = (-b+cmath.sqrt(disc))/(2*a)
#s2 = (-b-cmath.sqrt(disc))/(2*a)
s1 = (-b+math.sqrt(disc))/(2*a)
s2 = (-b-math.sqrt(disc))/(2*a)
print ("The solutions are " + format(s1,",.2f"),"and " + format(s2,.2f"))
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。