为什么我的整数被转换成浮点数?

时间:2014-02-11 00:15:37

标签: python python-3.x

目前正在编写一个分配来编写创建分数的类。该课程的前几行如下:

class Fraction():
    #constructor
    """
    Post-condition:  User calls class with 0, 1, or 2 integers.
    Post-condition:  Fraction object is created.  Numerator and denominator each default
    to 1.

    """
    def __init__(self, numerator = 1, denominator = 1):
        self.__numerator = numerator
        self.__denominator = denominator

    #__str__ method
    """
    Pre-condition:  User has created a fraction object and has call the print function
    to display the fraction value.
    Post-condition: Method checks for a denominator of zero and returns an error message
    if true.  It will then check for float values in the numerator and denominator and 
    convert them to integers if true.  It will then check if the numerator and denominator
    are the same number and return a 1 if true. Next it checks if the denominator can be 
    divided into the numerator with a zero remainder and returns a whole number if true.
    Last, it will return a fraction.

    """
    def __str__(self):
        #check for float in denominator
        if isinstance(self.__denominator, float):
            self.__denominator = int(self.__denominator)
        #check for float in numerator
        if isinstance(self.__numerator, float):
            self.__numerator = int(self.__numerator)
        #check for equality in numerator and denominator
        if self.__numerator == self.__denominator:
            return 1
        #check for zero remainder division 
        elif self.__numerator % self.__denominator == 0:
            wholeNumber = self.__numerator / self.__denominator
            return str(wholeNumber)
        else:
            divisor = self.__numerator
            tmpDenom = self.__denominator
            while tmpDenom:
                divisor, tmpDenom = tmpDenom, divisor % tmpDenom
            self.__numerator = self.__numerator // divisor
            self.__denominator = self.__denominator // divisor
            return str(self.__numerator) + '/' + str(self.__denominator)

在终端和IDLE中运行我的测试时,我使用以下代码来测试输出:

from modFraction import Fraction

frac1 = Fraction(15, 16)
print(frac1)
frac2 = Fraction(17, 18)
print(frac2)
print(frac1 + frac2)

当我运行输出时,我最终得到以下输出:

15.0/16.0
17.0/18.0
271.0/144.0

我的整数输入转换为浮点数在哪里???

2 个答案:

答案 0 :(得分:3)

我认为解决方案是在IDLE中使用内置的“运行模块”有时会对输出做一些非常愚蠢的事情 - 在终端中运行会给你int作为输出。


其他一些提示:

在Python 3中,/总是返回一个浮点数。 See PEP 238

此外,带有混合参数的//(float和int)将返回一个float:

  

特别是,如果a和b都是int或long,结果就是       与这些类型的经典除法相同的类型和价值       (包括混合输入类型的情况; int // long和long // int       将返回长)。

答案 1 :(得分:0)

Can't reproduce包含您提供的代码。

请注意,在Python 3中,即使两个操作数都是整数,常规除法运算符也总是返回一个浮点数。这是从Python 2改变的,当两个操作数都是整数时,常规除法运算符将使用整数除法。您可以使用双斜杠运算符强制使用整数除法(例如,在Python 2和Python 3中都使用7 // 3 == 2)。

不相关的提示:在处理分数时,divmod()方法非常有用。它同时给出整数除法和余数。