【问题标题】:Why are my integers being converted to floats?为什么我的整数被转换为浮点数?
【发布时间】:2014-02-11 08:36:58
【问题描述】:

目前正在写一个作业来编写一个创建分数的类。类的前几行如下:

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

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

【问题讨论】:

  • 为什么__str__方法中有这么多类型检查和转换?这一切都应该发生在__init__,而不是在需要打印的时候。
  • 当我运行print(Fraction(15, 16)) 时,我得到15/16。仔细检查您正在运行的 Python 版本,也许?
  • @Blackwell 有时,如果您有旧的 .pyc 文件,就会发生巫术。删除相关目录下的所有.pyc文件,然后重试。
  • @juliohm:因为这是一个作业。
  • @jozzas:谢谢。我想我的运气不好是 IDLE ......不会发生在终端。

标签: python python-3.x


【解决方案1】:

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


其他一些提示:

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

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

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

【讨论】:

  • 这是真的,但不相关。
  • 虽然这是真的(/ 在参数为complexfractions.Fractiondecimal.Decimal 等时不会返回浮点数),它可能是问题的原因,我们无法从显示的代码中分辨出来。
  • 我认为这真实又相关。 OP 执行self.__numerator = self.__numerator // divisor,如果self.__numeratorfloat,他们将获得float
  • @SethMMorton:但self.__numerator 不应该是浮点数。事实上,__str__ 明确确保它不是浮点数,这有点奇怪。
  • @user2357112 是的,我在发表评论后注意到了这一点。这可能是 .pyc 的问题。
【解决方案2】:

Can't reproduce 使用您提供的代码。

请注意,在 Python 3 中,常规除法运算符始终返回浮点数,即使两个操作数都是整数。这与 Python 2 有所不同,在 Python 2 中,当两个操作数都是整数时,常规除法运算符将使用整数除法。您可以通过使用双斜杠运算符强制使用整数除法(例如 Python 2 和 Python 3 中的 7 // 3 == 2)。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多