Skip to main content
 首页 » 编程设计

python之这个 python 脚本会按预期工作吗我想让它把随机数代入一个等式直到它得到 187.2

2025年05月04日16mate10pro

print("Getting possible numbers") 
import random 
 
h1 = random.uniform(0,30) 
h2 = random.uniform(0,30) 
h3 = random.uniform(0,30) 
t = random.uniform(0,30) 
 
baset = .5 * t * h3 
volumeti = baset * h2 
baser = t * h2 
volumer = h1 * baser 
volumetotal = volumeti + volumer 
c = 1 
 
if volumetotal == 187.2: 
  print("h1=", h1, "h2=", h2, "h3=", h3, "t=", t) 
 
while volumetotal != 187.2: 
 c += 1 
 print("Wrong, trying again", c) 

它会找到六棱柱的体积,但需要很长时间,我还没有得到输出。

请您参考如下方法:

循环:

while volumetotal != 187.2: 
 c += 1 
 print("Wrong, trying again", c) 

是一个陷阱。一旦进入循环,就永远无法退出,因为您没有更改循环体中的 volumetotal。

另请注意,检查 float 是否相等可能很棘手。两个数字可能非常接近(10**16 中的 1 分之一)但仍然不同——而且这种大小的数字错误一直在发生。