首页 > 解决方案 > 将数字保存到变量

问题描述

我必须找到最小的正数(不等于0)并将其保存到变量“small”和小于无穷大的最大正数(math.inf)并将其保存到变量“great”。到目前为止,我的代码看起来像这样:

x = float(1)
import math 

small = x/2
while small > 0:
    small = small/2
    print(small)

y = float(1)    
great = y*2
while great < math.inf:
    great = great*2
    print(great)

它打印数字列表,但问题是 Python 保存了“small= 0”和“great= inf”。如何保存所需的数字,而无需从我从代码中获得的列表中手动输入它们?

标签: pythonpython-3.xlistvariables

解决方案


你应该打破之前的第一个循环small变成0,并且之前的第二个循环great等于无穷大:

import math

small = 1
while True:
    if small / 2 == 0:
        print(small)
        break
    small /= 2

great = float(1)
while True:
    if great * 2 == math.inf:
        print(great)
        break
    great *= 2

这输出:

5e-324
8.98846567431158e+307

推荐阅读