[英]Creating 1 decimal place
因此,使用運行猜謎游戲的這段代碼,我或多或少已完全完成。 最后,它將打印所有已玩游戲的總結果。 這包括總游戲數,總猜測數,平均猜測數/游戲和最佳分數。 除了我需要平均猜測/游戲以顯示小數點后第System.out.printf("Guesses/game = %.1f")
之外,我已經全部解決了,但是System.out.printf("Guesses/game = %.1f")
無法正常工作,idk為什么
import java.util.*; //so I can use scanner
public class GuessingGame {
public static void main(String[] args) {
Random rand = new Random ();
int max = 100;
Scanner input = new Scanner(System.in);
int guess;
boolean play = true;
int totalGames = 0;
int totalGuesses = 0;
int bestGame = Integer.MAX_VALUE;
System.out.println("Can you guess the word?");
System.out.println("I am sure you cannot guess!");
System.out.println("Go ahead and try!");
System.out.println();
while (play) { //repeats until user enters a statement besides y when asked to play again
System.out.println("I'm thinking of a number between 1 and " + max + "...");
int numberToGuess = rand.nextInt(max) + 1;
int numberOfTries = 0;
boolean win = false;
while (!win) {
System.out.print("Your guess? ");
guess = input.nextInt();
numberOfTries++;
if (guess == numberToGuess) {
win = true;
} else if (guess > numberToGuess) {
System.out.println("It's lower.");
} else if (guess < numberToGuess) {
System.out.println("It's higher.");
}
input.nextLine();
}
if (numberOfTries == 1) {
System.out.println("You got it right in " + numberOfTries + " guess!");
} else {
System.out.println("You got it right in " + numberOfTries + " guesses!");
}
totalGames++;
totalGuesses+= numberOfTries;
System.out.print("Do you want to play again? ");
String answer = input.nextLine();
char firstLetter = answer.charAt(0);
if (firstLetter == 'y' || firstLetter == 'Y') {
play = true;
} else {
play = false;
bestGame = Math.min(bestGame, numberOfTries);
}
System.out.println();
}
System.out.println("Overall results:");
System.out.println("Total games = " + totalGames);
System.out.println("Total guesses = " + totalGuesses);
System.out.printf("Guesses/game = ", totalGuesses/totalGames);
System.out.println("Best game = " + bestGame);
}
}
totalGuesses和totalGames都是整數,因此當您將它們除以整數時,%f需要一個浮點數。
而是將一個強制轉換為浮點數以進行浮點除法:
totalGuesses/(double)totalGames
如果由於某種原因您只是得到了錯誤的輸出,請嘗試使用十進制格式化程序:
DecimalFormat formatter = new DecimalFormat("#.#");
System.out.println(formatter.format(avgGuesses)); //or whatever your var name is
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.