1

我有一个应用程序猜数字游戏,用户必须猜一个 0 到 100 之间的数字,当他们猜对时,程序会询问他们是否想在玩完游戏后再次玩游戏中最多的猜测次数。现在我得到的只是他们在使用“Math.min(,)”时所有猜测的总和?如何让最小功能起作用???功能代码在下面。

  1. minimumNumGuesses = Math.min(leastNumGuesses,guesses);

    double rightNum = Math.random() *100;
    int randomNum = (int) rightNum; //convert the random number to int
    int tries = 0; //single game gussess output
    int numberOfGames = 0;
    int allTries = 0; //accumalates all tries(sum of all tries)
    int guesses = 0; // guesses of all games combined
    int gameGuesses = 0;
    int leastNumGuesses = 100;
    int mostNumGuesses = 0;
    
    
      while (choice.equalsIgnoreCase("y"))
    

    {

       System.out.println();
    
       int guess = getIntWithinRange(sc,"Enter the Number: ", 0, 100);
       tries++;
       guesses++;
       gameGuesses++;
    
       if (guess == randomNum)
       {
           numberOfGames++;
           System.out.println("You got it in " + tries + " tries.");
           leastNumGuesses = Math.min(leastNumGuesses,gameGuesses);
           if (tries <=3)
                    System.out.println("Great work! You are a mathematical wizard.");
           else if (tries > 3 && tries <= 7)
                    System.out.println("Not too bad! You've got some potential.");
           else if (tries > 7)
                    System.out.println("What took you so long? Maybe you should take some lessons.");
    
           System.out.println();      
           System.out.println("Would you like to play again (y/n):");
           choice = sc.nextLine();
    
       while (!choice.equalsIgnoreCase("n") && !choice.equalsIgnoreCase("y"))
        {
    
       System.out.println("Error! entry must be \"y\" or \"n\".");
       System.out.println("Would you like to play again (y/n):");
       choice = sc.nextLine();
        }   
    
           if (choice.equalsIgnoreCase("y"))       
           {    // reset the random number & tries
    
              rightNum = Math.random() *100;
                randomNum = (int) rightNum;
                tries=0;
               gameGuesses++;
           }
           else if (choice.equalsIgnoreCase("n"))
           {    
              allTries += guesses;
              int averageNumGuess = allTries / numberOfGames;
    
               System.out.println("Bye - Come back again");
               System.out.println("Number of Games Played: " + numberOfGames);
               System.out.println("Average Number of Guesses: " + averageNumGuess);
               System.out.println("Least Amount of Guesses In a Single Game: " + leastNumGuesses);
    
           }
    
       }
    
4

1 回答 1

0

看起来你正在改变你想要guesses在程序中间代表的东西。

请记住,这guesses是所有游戏的猜测总数leastNumGuesses,最初设置为100。在大多数情况下,您会发现guesses < leastNumGuesses,因此该Math.min(guesses, leastNumGuesses)函数将返回guesses

解决方法:使用除 之外的变量guesses,例如,gameGuesses跟踪游戏中进行了多少次猜测。然后,Math.min(,)将按照您的预期行事。

于 2013-03-05T02:37:50.307 回答