【问题标题】:Printing number with decimal point打印带小数点的数字
【发布时间】:2012-01-27 20:28:20
【问题描述】:

嗯,我在打印带小数点的数字时遇到了麻烦。 当我运行 python 并要求它进行除法时,结果必须是带小数点的数字,它不会打印小数点。 比如我刚刚做了这个算法:

print 'Report card calculation'
grade1 = input ('Insert the first grade: ')
grade2 = input ('Insert the second grade: ')
grade3 = input ('Insrt the third grade: ')

media = (grade1 + grade2 + grade3) / 3
print 'Your final result is', media

但是当它打印“媒体”时,应该有小数点的数字没有小数点。我该如何解决?

【问题讨论】:

  • 您的意见是什么?它们是整数吗?

标签: python floating-point type-conversion


【解决方案1】:

最简单的改变:除以3.0而不是3

media = (grade1 + grade2 + grade3) / 3.0

这将确保分配给media 的值将是浮点数,即使三个等级变量保持整数。

【讨论】:

    【解决方案2】:

    在文件顶部添加:

    from __future__ import division
    

    或者使用 3.0 而不是 3。在 Python 2 中,两个整数相除总是产生一个整数。

    【讨论】:

      【解决方案3】:

      您的操作被处理为整数除法,尝试使用 3.0 代替 3,看看会发生什么。

      【讨论】:

        【解决方案4】:

        当您在 Python 2.x 中将两个整数相除时,结果将是一个整数。来自Numeric Types的文档:

        对于(普通或长)整数除法,结果是整数。结果总是向负无穷取整:1/2 为 0,(-1)/2 为 -1,1/(-2) 为 -1,(-1)/(-2) 为 0。请注意如果任一操作数是长整数,则无论数值如何,结果都是长整数。

        要获得您想要的行为,请将from __future__ import division 添加到模块顶部以使用Python 3 division behavior,或者将分子或分母(或两者)更改为浮点数:

        # either of the following would work
        media = float(grade1 + grade2 + grade3) / 3
        media = (grade1 + grade2 + grade3) / 3.0
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-09-11
          相关资源
          最近更新 更多