6.32(游戲:贏取雙骰子賭博游戲的機會)修改編程練習題6.30使該程式運行10000次,然後顯示贏得游戲的次數 6.32(Game: chance of winning at craps)Revise Exercise 6.30 to run it 15,000 times and display ...
**6.32(游戲:贏取雙骰子賭博游戲的機會)修改編程練習題6.30使該程式運行10000次,然後顯示贏得游戲的次數
**6.32(Game: chance of winning at craps)Revise Exercise 6.30 to run it 15,000 times and display the number of winning games.
下麵是參考答案代碼:
// https://cn.fankuiba.com
public class Ans6_32_page205 {
public static void main(String[] args) {
int count = 0;
for (int c = 0; c < 10000; c++) {
int guessOne = random(6);
int guessTwo = random(6);
int guessThree;
int sum = guessOne + guessTwo;
int guessTemp = 0;
boolean nextGuess = true;
//System.out.println("You rolled " + guessOne + " + " + guessTwo + " = " + sum);
if (sum == 7 || sum == 11) {
count = count + 1;
//System.out.println("You win");
} else if (sum == 2 || sum == 3 || sum == 12) {
//System.out.println("You lose");
}
else {
while (nextGuess) {
//System.out.println("point is " + sum);
guessThree = random(6);
if (guessThree == 7) {
//System.out.println("You rolled 7 + " + guessThree + " = " + (guessThree * 2));
//System.out.println("You win");
count++;
nextGuess = false;
} else if (guessThree == guessOne || guessThree == guessTwo || guessThree
== guessTemp) {
//System.out.println("You rolled " + guessThree + " + " + guessThree + " = " + (guessThree * 2));
//System.out.println("You win");
count++;
nextGuess = false;
} else {
//System.out.println("You rolled " + guessThree + " + " + sum + " = " + (guessThree + sum));
//System.out.println("You lose");
break;
}
guessTemp = guessThree;
}
}
}
System.out.println(count);
}
public static int random(int guess) {
return 1 + (int) (Math.random() * guess + 1);
}
}
適用Java語言程式設計與數據結構(基礎篇)(原書第11版)Java語言程式設計(基礎篇)(原書第10/11版)更多內容