samedi 24 janvier 2015

Random guesses confusion

I am writing a method that prints guesses = [random number here from 1-50 inclusive] multiple times on a new line until the value is larger than 48. Once it is larger than 48 I try to print the number of guesses it took (No scanner used though, the 'guesses' are the number produced by the Math.random). Here is example output:



guess = 43
guess = 47
guess = 45
guess = 27
guess = 49
total guesses = 5


and this is my output:



guess = 42.84000000000028
guess = 46.0
guess = 44.0
guess = 26.0
total guesses = 4


The reason I am getting almost the same random numbers is because it's in Practice-It. One more thing, I have tried to make the random number an int by replacing double with int but that resulted in an 'mismatch between data types'.


Here is my code:



public static void makeGuesses(){
int totalGuesses = 0;
double randomNumber = (Math.random() * 51);

while(randomNumber < 48){
System.out.print("guess = ");
System.out.println(randomNumber);
randomNumber = (int)(Math.random() * 51);
totalGuesses++;
}
System.out.print("total guesses = " + totalGuesses);
}




Aucun commentaire:

Enregistrer un commentaire