我想为这个计算编写一个代码:
3.3+4.8*6-4/2
这是我的代码:
from decimal import *
a = Decimal('3.3') + Decimal('4.8') * 6
b = 4 / 2
c = a - Decimal(str(b))
print(c)
以上代码可以给出正确的答案: 30.1。但我认为这太复杂了,应该有一个更简单的解决办法。有人能给出一个简化的代码吗?谢谢。
发布于 2022-05-14 08:40:55
根据您提供的计算,不清楚您是否会在其中使用不同的变量,或者您是否只想计算这个特定的等式。如果您只想计算这个方程,请计算"(3.3 + 4.8 * 6.0) - 2.0“,因为您实际上不需要4/2的计算器。
result = 3.3 + 4.8 * 6.0 - 2.0
print(round(result, 2)) #round() to "render" floating-point error
但是,如果它将多次用于不同的变量,您应该定义一个函数,例如(假设方程中的所有数字都是变量):
def eq_evaluation(a, b, c, d, e):
return round((a + b * c - d / e), 2)
此外,通配符导入(from package import *
)不是python中的最佳实践。例如,参见:关于它的This question。
发布于 2022-05-14 08:39:42
假设python 3:
print(3.3+4.8*6-4/2)
# 30.099999999999994
print('{:.2f}'.format(3.3+4.8*6-4/2))
# 30.10
https://stackoverflow.com/questions/72238271
复制相似问题