Python:如何使用小数而不是舍入?

时间:2015-03-04 19:33:15

标签: python decimal calculator

好的,我知道如何在Python中通常使用小数和数学计算。但这些使用变量。所以我不知道如何在我的实例中做到这一点。这是我快速输入的计算器,但我不知道如何使用小数。非常感谢!!

def addition(a, b):
    return a + b

def subtraction(a, b):
    return a - b

def multiplication(a, b):
    return a * b

def division(a, b):
    return a / b

print """\nThis is a calculator. You can add, subtract, multiply, or divide with a max of two variables."""

print """\nTo add: Type 1
\nTo subtract: Type 2
\nTo multiply: Type 3
\nTo divide: Type 4 """

sign = raw_input("\n\nPlease enter a number  >")


if sign == "1":
    first = int(raw_input("\n\nEnter your first number to add  >"))
    second = int(raw_input("\n\nEnter your second number to add  >"))
    print "\nYour result is:\n"
    print addition(first, second)


elif sign == "2":
    first = int(raw_input("\n\nEnter your first number to subract  >"))
    second = int(raw_input("\n\nEnter your second number to subract  >"))
    print "\nYour result is:\n"
    print subtraction(first, second)

elif sign == "3":
    first = int(raw_input("\n\nEnter your first number to multiply  >"))
    second =int(raw_input("\n\nEnter your second number to multiply  >"))
    print "\nYour result is:\n"
    print multiplication(first, second)

elif sign == "4":
    first = int(raw_input("\n\nEnter your first number to divide  >"))
    second =int(raw_input("\n\nEnter your second number to divide  >"))
    print "\nYour result is:\n"
    print division(first, second)

2 个答案:

答案 0 :(得分:3)

而不是int(...)使用float(...)decimal.Decimal(...)

示例:

import decimal
d = decimal.Decimal(raw_input("\nEnter a number >"))
print(d)

或:

f = float(raw_input("\nEnter a number >"))
print(f)

答案 1 :(得分:1)

如果你不介意丢失精度使用浮点变量。

如果你想保持精确度,我建议使用它:

https://docs.python.org/2/library/decimal.html

..而不是滚动你自己的十进制数学库。