我试着做一个简单的“投资游戏”。但由于某种原因,可变现金在“投资”后仍显示为1000英镑。我也想让这个游戏持续下去。就像玩家可以继续玩游戏,赚/赔现金一样。程序在下面!谢谢
import sys
import random
print "INVEST"
cash = 1000
highlow = ["h", "l"]
percentrand = random.randint(1,99)
percentup = percentrand/100 + 1
percentdown = percentrand/100 - 1
randomhighlow = random.choice(highlow)
print "You have 1000$ on you now."
investquit = raw_input("Invest or quit?")
if investquit.lower() == "quit":
quit()
elif investquit.lower() == "invest":
if randomhighlow == "h":
cash == cash*percentup
print str(cash) + ",up," + str(percentrand) + "%"
if randomhighlow == "l":
cash == cash*percentdown
print str(cash) + ",down," + str(percentrand) + "%"
你有几个问题。其他答案和评论涵盖了其中的大部分,但我将把它们合并成一个答案
首先,当您应该使用浮点除法时,您使用的是整数除法。这在Python3.x中是可行的,但是由于您将其标记为2.7,所以它是不同的:
与“向下”相同,只是您将从1中减去1而不是:
那么您使用了错误的运算符来赋值
cash
:而且在你发布代码时,代码中有不正确的缩进
最后,你需要一个循环来继续玩:
这似乎奏效了:
你没有循环来运行程序多次。此外,在Python2.7中,将两个int除以将产生另一个int,而不是一个float。这就是你的主要问题,因为这是造成百分比上升或下降总是1
所以你应该这样做:
双等于
==
是比较运算符,而单等于=
是赋值运算符在你的情况下有现金价值更新你想要的
(并相应地向下移动)
无限制地玩游戏,或直到某个特定条件(即现金>;0)您可以在while循环中围绕整个对象,例如
编辑:正如Ryan正确地提到的,您希望
percentrand = float(random.randint(1,99))
确保除法结果不是整数相关问题 更多 >
编程相关推荐