创建1个小数位

时间:2015-05-07 21:01:13

标签: java while-loop decimal

所以我或多或少完全使用这个运行猜谜游戏的代码。最后它打印所有比赛的总结果。这包括总游戏,总猜测,平均猜测/游戏和最佳分数。我已经完成了所有工作,除了我需要平均猜测/游戏显示1位小数但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);
   }  
}

2 个答案:

答案 0 :(得分:1)

totalGuesses和totalGames都是整数,所以当你划分它们时你得到一个整数,而%f需要一个浮点数。

而是将一个转换为浮点数的浮点数:

totalGuesses/(double)totalGames

答案 1 :(得分:0)

如果由于某种原因您只是输错了输出,请尝试使用小数格式化程序:

DecimalFormat formatter = new DecimalFormat("#.#");
System.out.println(formatter.format(avgGuesses)); //or whatever your var name is