当我输入50时,我想得到下面程序的输出为122.00,但它就像122.0,在这种情况下我需要2位数字输出

问题描述 投票:0回答:2
def temp_converter(_value):

    fahrenheit = (_value*9.00/5.00)+32.00
    fahrenheit = round(fahrenheit,2)
    print(f"Temparature in fahrenheit : {fahrenheit}")
celcius = float(input(": "))

temp_converter(celcius)

输出如下:

122.0

但我想要 122.00。

python
2个回答
0
投票
def temp_converter(_value):
    fahrenheit = (_value * 9.00 / 5.00) + 32.00
    fahrenheit = f"{fahrenheit:.2f}"  # Format to 2 decimal places
    print(f"Temperature in fahrenheit: {fahrenheit}")
celcius = float(input("Enter temperature in Celsius: "))
temp_converter(celcius)

0
投票

所以这里的问题是您必须定义输出中想要多少位小数。

让我更正您的代码。

def temp_converter(_value):
    fahrenheit = (_value * 9.00 / 5.00 )+32.00
    fahrenheit = round(fahrenheit, 2)
    print(f"Temperature in fahrenheit: {fahrenheit:.2f}")
celcius = float(input("Enter temperature in Celsius: "))
temp_converter(celcius)

如您所见,我在打印语句中的变量华氏度末尾输入了“:.2f”,以定义我想要在输出中显示的小数位数。

不要忘记 Python 中的缩进

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