试图做简单的数学运算

时间:2016-06-18 08:40:41

标签: python python-2.7 python-3.x math

我试图在python中弄清楚的是,我在投注游戏中投入4美分,但如果我输了,那么我的原始投注是2x 每次时间我输了。所以我想看看在达到极限(500)之前我得到了多少尝试。

doStartUp

3 个答案:

答案 0 :(得分:1)

meme = 2
while True:
    meme = meme + 2
    count = 0
    for x in range(0, 500, 4*meme):
        count +=1
        meme = meme + 2
    print count
    raw_input()

答案 1 :(得分:1)

您的代码

我真的不知道你的代码试图做什么,但我会提到一些肯定不会出现的错误。

meme = 2
# You will never break out of the loop
while True:
    meme = meme + 2
    # I don't think you wanted to step 4*meme times
    for x in range(0, 500, 4*meme):
        meme = meme + 2
        print(x)

解决问题

您应该做的是将变量乘以并在amount大于0时扣除amount变量。

starting_amount = 500
starting_bet = 4

bet = starting_bet
amount = starting_amount
count = 0
while amount > 0:
    amount -= bet
    bet *= 2
    count += 1

print(count)

代码将吐出:

$> python test.py
7

$>

更好的方法

重新阅读问题之后,我想到了一个更好的解决方案,根本不需要循环!您可以使用math模块中的对数来执行此操作。

from math import log, floor
# You can change these
bet = 4
amount = 500
multiplier = 2
# Calculations
n = log(bet, multiplier)
print(floor(log(amount, multiplier) - n) + 1)

答案 2 :(得分:0)

sum = 4
print (sum)
i = 0

for i in range (500):
    sum = sum * 2
    print (sum)
    i = i + 1
    if (sum > 500):
        break

print("you can do it " + str(i) + " times")