【问题标题】:In python how do I get floats to display what I'm trying to display?在 python 中,如何让浮点数显示我想要显示的内容?
【发布时间】:2018-02-08 21:29:06
【问题描述】:

在 truecount() 中,无论我将 float() 放在哪里,当它应该给我大约 0.505 时,它总是返回 1.0。我知道这可能与我格式化所有内容的方式有关,但对于我做错的任何帮助将不胜感激。 p.s.我对编程很陌生

def count():
    global totalCards
    global cardCount
    card = int(raw_input("input card. "))
    totalCards = totalCards - 1
    if card == 1:
        print "card invalid"
    else:
        if card <= 6 and card > 1:
            cardCount = cardCount + 1
        elif card == 10:
            cardCount = cardCount - 1
        elif card >= 7 and card <= 9:
            cardCount = cardCount
    return

def truecount():
    global cardCount
    global truecardCount
    global totalCards
    global decks
    decksRemaining = float(totalCards/52)
    truecardCount = float(cardCount / decksRemaining)
    return

def main():
    run = True
    totalCards = 0
    cardCount = 0
    truecardCount = 0.0
    while run == True:
        print "Welcome to my card counter. Start using when dealer 
shuffles."
        user_input = raw_input("Type R When you're ready to start. Type X if 
you want to quit.")
        if user_input.upper() == "R":
            global truecardCount 
            truecardCount = 0
            global cardCount
            cardCount = 0
            runCount = True
            decks = int(raw_input("What is the amount of decks in the shoe? 
"))
            global totalCards 
            totalCards = decks * 52
            while runCount == True:  
                count()
                truecount()
                print(float(truecardCount))
        elif user_input.upper() == "X":
            run == False
        else:

【问题讨论】:

  • float 应用到除法的结果不会使除法不是浮点除法。它只是让你得到你本来会得到的整数,但表示为一个浮点数。
  • totalCards/52.0代替float(totalCards/52)
  • 在 Py3 中 division 处理更改,因此您可以使用 __future__,例如:from __future__ import division 来提出 Py3 行为。

标签: python python-2.7 types floating-point


【解决方案1】:

这里:decksRemaining = float(totalCards/52) 你正在除以一个整数。

如果您使用的是 Python 2.7,除以整数除以整数将得到整数结果。例如。 5/2 会给你2

所以,您可以通过totalCards/52.0 获得您想要的结果。

或者,要使用 Python 3+ 除法,您可以执行以下操作: from __future__ import division 然后除法应该像你期望的那样工作,即5/2会给你2.5

【讨论】:

    【解决方案2】:

    在将转换应用于浮点数之前,您正在执行整数除法。在 Python 2.x 中,整数除法返回一个整数,而不是浮点数。

    您有多种选择:

    • decksRemaining = totalCards/52.0
    • decksRemaining = float(totalCards)/52
    • from __future__ import divisiondecksRemaining = totalCards/52(这样您就有 Python 3.x 的整数除法行为)

    【讨论】:

      猜你喜欢
      • 2019-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多