如何获得十进制和整数的输出?

2024-09-30 13:22:34 发布

您现在位置:Python中文网/ 问答频道 /正文

这是华氏到摄氏的转换。我将它设置为2个小数点作为输出,但是假设用户输入50,它将显示为10.00。我怎样才能让它变成10而不带小数点,但允许小数点不是整数?你知道吗

temp = float(input(" Fahrenheit temperature: "))
celsius = float((5/9)*(temp - 32))
print("The temperature in celsius is: {:.2f}°.".format(celsius))

Tags: the用户informatinputis整数float
3条回答

您需要单独执行此操作,因为与50“足够接近”以显示为50的内容是特定于应用程序的。你知道吗

if abs(celsius % 1) < 0.001  # Or whatever threshold you want:
    print("The temperature in celsius is: {:d}°.".format(int(celsius//1)))
else:
    print("The temperature in celsius is: {:.2f}°.".format(celsius))

您可以尝试以下方法:

temp = float(input(" Fahrenheit temperature: "))
celsius = float((5/9)*(temp - 32))
if (celsius % 1 == 0):
    print("The temperature in celsius is: {}°.".format(celsius))
else:
    print("The temperature in celsius is: {:.2f}°.".format(celsius))

if条件检查您是否有整数。你知道吗

试试这个:

def doTheThing(number):
    numString = str(number)
    i = len(numString) -1
    while True:
        if numString[i] == ".":
            numString = numString[:-1] #remove the .
            break
        if numString[i] == "0":
            numString = numString[:-1] #remove the 0
        else:
            break
        i-=1
    print(numString)



x = 10.0
doTheThing(x)

这将打印10,其中常规打印将返回10.0

可能有更好的方法,但这很管用;)

相关问题 更多 >

    热门问题