在python3.5中如何选择小数点后的第一个数字?

2024-10-01 09:33:54 发布

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

我现在正在学习Python(到目前为止我很喜欢它),并且制作了一个小的华氏/摄氏度转换器。在

这是运行时的输出:

Please enter the degrees in Fahrenheit or Celsius to convert: 32

32.0 degrees Celsius is 89.6 degrees Fahrenheit.

32.0 degrees Fahrenheit is 0.0 degrees Celsius.

Do you want to calculate again? (y/n):

这就是我想要的,除非小数后面的数字是0(整数),我想完全去掉.0(即5.0到5)。我想我需要一个if语句来测试它是否等于零,但是我该如何选择这个值呢?在

完整代码:

answer = "ERROR"

def calcfc():
""" Calculates F to C and C to F, prints out,
    and asks if user wants to run again """
    try:
        degrees = float(input("\nPlease enter the degrees in Fahrenheit or Celsius to convert: "))
    except Exception:
        input("\nEnter a valid number next time. Hit enter to terminate.")
        exit()

    ftoc = (degrees - 32) * 5 / 9
    ctof = (degrees * 9) / 5 + 32

    print("\n{} degrees Celsius is {:.1f} degrees Fahrenheit.".format(degrees, ctof))
    print("{} degrees Fahrenheit is {:.1f} degrees Celsius.".format(degrees, ftoc))
    global answer
    answer = input("\n\nDo you want to calculate again? (y/n): ")

calcfc()

# run again?
while answer != "y" and answer != "n":
    answer = input("\nPlease enter y for yes or n for no: ")
while answer == "y":
    calcfc()
if answer == "n":
    exit()

Tags: orandthetoanswerininputif
3条回答

如果数字以.0结尾,则必须将其转换为字符串并进行测试:

number = 23.04
text = "{:.1f}".format(number)
if text.endswith(".0"):
    text = text[:-2]

数字的小数部分如下:

>> num = 42.56
>> decimal_part = num - int(num)
>> decimal_part = 0.56

Thispost探讨了一个类似的问题。在

args = [89.6, 32.0, 5.5, 10.0, 9.1]

for var in args:
    if var == int(var):
        print int(var) # prints the number without the decimal part
    else:
        print var

输出

^{pr2}$

相关问题 更多 >