public class Main {
public static void main(String[] args) {
int [] numbers = new int [10];
for (int i = 0; i < 10; i++) {
int tempNum = Math.random() * 20; //possible loss of precision error?
}
for (int i = 0; i < 10; i++) {
System.out.println ("Number " + i + " : " + numbers[i] );
}
}
}
Math.random problem
Page 1 of 18 Replies - 482 Views - Last Post: 01 May 2011 - 08:58 AM
#1
Math.random problem
Posted 01 May 2011 - 07:16 AM
Hey all, I'm trying to randomize a bunch of numbers into an integer array however when I do, I get a "possible loss of precision error", I can change my tempNum variable to double however I wish to use an integer array, is there a way to fix this? My code is below:
Replies To: Math.random problem
#2
Re: Math.random problem
Posted 01 May 2011 - 07:28 AM
You need an explicit cast
int tempNum = (int)(Math.random() * 20);
#3
Re: Math.random problem
Posted 01 May 2011 - 07:36 AM
If you get int not double you'll should use class Random. In class Random is found function which is return int. You can see example code: http://www.javapract...Action.do?Id=62
#4
Re: Math.random problem
Posted 01 May 2011 - 08:00 AM
Math.random() returns a double type answer and you need to store it in an Integer array. to do it just type cast it
#5
Re: Math.random problem
Posted 01 May 2011 - 08:06 AM
Oh... ok, what exactly does this casting do? My code works now but I'm not 100% sure as to what the code does? Sorry I'm new to java.
#6
Re: Math.random problem
Posted 01 May 2011 - 08:15 AM
casting converts data from one type to another. see java tutorials for more reference.
#7
Re: Math.random problem
Posted 01 May 2011 - 08:48 AM
Thanks! Wow this website is awesome
#8
Re: Math.random problem
Posted 01 May 2011 - 08:56 AM
We all knew that it was!
Casting basically takes data that was stored in memory as a certain data structure and then stores it in memory with the same size (generally) but as a different data type, the old data is lost when you cast the variable. Concerning your randomizing of integers using Math.random(), this may provide a better explanation.
http://www.java-exam...ing-math.random
http://www.java-exam...ing-math.random
#9
Re: Math.random problem
Posted 01 May 2011 - 08:58 AM
Thanks, I have basically gathered that: the "(int)" parses the double of Math.random()*n to an int value.
Page 1 of 1
|
|

New Topic/Question
Reply



MultiQuote






|