为什么无论我做什么,列表中的第一个变量都不会打印到小数点后 3 位?

问题描述 投票:0回答:1

基本上这是我的代码,但每次我创建第一个参数时< 3 decimal places and try make it be converted to 3 d.p it won't do it. it will just add it to the list how i wrote it. like if StartVal is 9.13, it won't print in the list as 9.130, it will still be 9.13. i've tried round function, formatting etc idk what to do please. help. also when the number added to the list is also an interger it will only print to one d.p. Like 27 will only print to 27.0 instead of 27.000. HELP PLEASE

import math

def generate_num(LowNum, HighNum):
    
    try:
        LowNum = float(LowNum)
        HighNum = float(HighNum)

    except ValueError:
        return False
    except KeyboardInterrupt:
        quit()

    LowNum = round(LowNum, 3)
    sequence = [LowNum]
    j = sequence[-1]

    while j <= HighNum:
        i = (math.sqrt((j) ** 3))
        i = round(i, 3)

        if i <= HighNum:
            sequence.append(i)
            j = i  
        else:
            break

    return sequence


print(generate_num(9, 923))
python list function parameters decimalformat
1个回答
0
投票

函数 round() 并不能确定列表打印时的格式。它只是将数字四舍五入到小数点后三位。 9.13 四舍五入至 3 位,仍为 9.13。 如果我理解正确的话,您希望数字的格式全部精确到小数点后 3 位。 为此,您必须使用某种字符串格式表达式。例如,您可以使用它代替 print():

for num in generate_num:
    print(f'{num:.3f}')

根据您的喜好,如果您还手动打印括号和逗号,则可以打印类似列表的内容。

© www.soinside.com 2019 - 2024. All rights reserved.