简体   繁体   English

如何让Python使用raw_input值作为固定点数?

[英]How can I make Python use a raw_input value as a fixed point number?

I'm making a unit converter just to practice. 我正在制作一个单位转换器来练习。 Currently, I've defined a function to figure out what type of conversion to make (distance, time, mass, etc.). 目前,我已经定义了一个函数来确定要进行的转换类型(距离,时间,质量等)。

It then calls the correct converter for the type, asks what you're converting from, what you're converting to, and what the value for conversion is. 然后它会为该类型调用正确的转换器,询问您要转换的内容,转换的内容以及转换的值。

def mass_converter():
    convert_from = raw_input('What unit are you converting from? ')
    convert_to = raw_input('What unit are you converting to? ')
    value = raw_input('How many of those do you have? ')

    if convert_from == "pounds" and convert_to == "kilograms":
        answer = float(value) * 0.453592
        print "That many pounds is %d kilograms." % answer
    elif convert_from == "kilograms" and convert_to == "pounds":
        answer = float(value) * 2.20462
        print "That many kilograms is %d pounds." % answer
    else:
        print "You have not selected a valid unit; please try again."
        mass_converter()

Currently, if I were to convert 10 pounds to kilograms, it tells me that the answer is 4 kilograms. 目前,如果我将10磅转换成公斤,它告诉我答案是4公斤。 It seems to be chopping off my decimals. 它似乎正在削减我的小数。 Obviously int(value) will do the same thing. 显然int(value)会做同样的事情。 What can I use to keep the exact value entered by the user? 我可以使用什么来保持用户输入的确切值?

The problem here is that you're using the %d format modifier in your string formatting which casts your answer to an integer. 这里的问题是你在字符串格式中使用%d格式修饰符,它将你的答案转换为整数。 Use %f instead (or even %s ). 使用%f代替(甚至%s )。

You could use %f instead of %d. 您可以使用%f而不是%d。 %d formats the number not as a floating point, but as a integer. %d将数字格式化为浮点数,而不是整数。 Alternatively you could use 或者你可以使用

  print "That many kilograms is {} pounds.".format(answer)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM