gpt4 book ai didi

java - 创建 1 位小数

转载 作者:行者123 更新时间:2023-12-01 11:34:50 25 4
gpt4 key购买 nike

所以我或多或少已经完全完成了运行猜谜游戏的代码。最后它会打印所有比赛的总结果。这包括总游戏数、总猜测数、平均猜测数/游戏数和最佳得分。我已经解决了所有问题,除了我需要平均猜测/游戏显示 1 位小数,但 System.out.printf("Guesses/game = %.1f") 不起作用,我不知道为什么

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需要一个 float 。

而是将 1 转换为 float 以进行浮点除法:

totalGuesses/(double)totalGames

关于java - 创建 1 位小数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30111559/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com