2
每当我执行程序时,平均变化总是0,我不明白为什么。Lucky Sevens [净变化计算]
/*LuckySevens.java
Simulate the game of lucky sevens until all funds are depleted.
1) Rules:
roll two dice
if the sum equals 7, win $4, else lose $1
2) The inputs are:
the amount of money the user is prepared to lose
3) Computations:
use the random number generator to simulate rolling the dice
loop until the funds are depleted
count the number of rolls
keep track of the maximum amount
4) The outputs are:
the number of rolls it takes to deplete the funds
the maximum amount
the average net change after 100 rolls
*/
import java.util.Scanner;
import java.util.Random;
public class LuckySevens {
public static void main (String [] args) {
Scanner reader = new Scanner(System.in);
Random generator = new Random();
int die1, die2, // two dice
dollars, // initial number of dollars (input)
countAtMax, // count when the maximum is achieved
count, // number of rolls to reach depletion
maxDollars, // maximum amount held by the gambler
averageWin, // the average net change after 100 rolls
initialDollars; // initial amount of money user has
// Request the input
System.out.print("How many dollars do you have? ");
dollars = reader.nextInt();
// Initialize variables
maxDollars = dollars;
initialDollars = dollars;
countAtMax = 0;
count = 0;
// Loop until the money is gone
while (dollars > 0){
count++;
// Roll the dice.
die1 = generator.nextInt (6) + 1; // 1-6
die2 = generator.nextInt (6) + 1; // 1-6
// Calculate the winnings or losses
if (die1 + die2 == 7)
dollars += 4;
else
dollars -= 1;
// If this is a new maximum, remember it
if (dollars > maxDollars){
maxDollars = dollars;
countAtMax = count;
}
/* TODO:FIX BELOW STATEMENT
it always returns influx as 0 */
if (count == 100) {
averageWin = ((maxDollars - initialDollars)/100);
System.out.println ("In the first 100 rolls there an average money influx of " + averageWin + " per roll.") ;
}
}
// Display the results
System.out.println
("You went broke after " + count + " rolls.\n" +
"You should have quit after " + countAtMax +
" rolls when you had $" + maxDollars + ".");
}
}
您多久测试一次该程序?因为很可能你会放松一些游戏,然后再也不会回头看看maxDollars。因此,您绝不会将maxDollars更改为initialDollars。这给你0/100 - > 0 – ceekay
可能的重复[在Java中总是结果为零(0)?](http://stackoverflow.com/questions/10455677/division-in-java-always-results-in -zero-0) – timrau
这个问题很可能是由于AverageWin是一个整数引起的。尝试将它改为浮点/双精度,以防止它被降低到下一个较低的整数(在您的情况下可能为0),并查看是否改变了结果。可能不是问题,但整数除法是第一件要吸引我的眼睛 – Sossenbinder