我试着计算一个玩家能用固定数量的钱玩多少回合的乐透和小丑游戏。
public static void example () {
int money = 200;
int lottoCost = 4;
int jokerCost = 3;
int costTogether = lottoCost+jokerCost;
int rounds = 0;
for (int i = money; i <= 0; rounds++) {
money = money-costTogether;
}
System.out.println("With " + money + " euros, you can play "
+ rounds + " rounds.");
System.out.println("");
}该代码目前打印文本“用200欧元,您可以播放0轮。”因此,它不向循环变量添加+1。我做错了什么?
发布于 2014-10-09 10:48:28
您的停止条件是错误的,所以循环永远不会被执行。您应该使用>=代替。此外,您也从不更改或使用i。
下面是一个经过修正的版本,使用currMoney而不是i更有意义。
int rounds = 0;
for (int currMoney = money; currMoney >= costTogether; currMoney -= costTogether) {
rounds++;
}但很明显,正如@Fredszaq在回答中指出的那样,你只需要一个简单的划分:
int rounds = money / costTogether;https://stackoverflow.com/questions/26276457
复制相似问题