Java Programming - Java.lang Class - Discussion

Discussion Forum : Java.lang Class - General Questions (Q.No. 1)
1.

What is the value of "d" after this line of code has been executed?

double d = Math.round ( 2.5 + Math.random() );

2
3
4
2.5
Answer: Option
Explanation:

The Math.random() method returns a number greater than or equal to 0 and less than 1 . Since we can then be sure that the sum of that number and 2.5 will be greater than or equal to 2.5 and less than 3.5, we can be sure that Math.round() will round that number to 3. So Option B is the answer.

Discussion:
10 comments Page 1 of 1.

Prerna said:   2 years ago
What if it would be;
double d = Math.round ( 5+ Math.random() +2.5);
the range will be (5.0,3.5)

Please anyone, help me by explaining this.
(1)

Rohit said:   5 years ago
Hi,

What if Math.random() returns 1.0 and the statement looks like;
double d = Math.round ( 2.5 + 1.0 );
Value of d will be 3.5 and Math.round(3.5) will be 4.0.

Aniket said:   5 years ago
@Anuj. Yes, it should be 3.0 but it's not in the option.

Anuj said:   6 years ago
Math.round (2.5 + Math.random() ) will return a double value, so the correct answer is 3.0 and not 3.

Pradeepsai.k said:   9 years ago
I agree with @Arijit Paul.

Ashish said:   1 decade ago
How I can check it out in my program ?

Arijit paul said:   1 decade ago
@Kavitha.

Math.random() "Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0."

Thus 2.5 + Math.random() will always be inside [2.5 to 3.5] range.

If the fractional portion of number is .5 or greater, the Math.round()rounded to the next higher integer. If the fractional portion of number is less than .5, the argument is rounded to the next lower integer.

So, The Math.round() of any number within this range[2.5 to 3.5] is 3.

Kavitha said:   1 decade ago
I have one doubt.

If Math.round () returns 0 then the answer may become 2.5 also is it correct or wrong?
(1)

Sandesh said:   1 decade ago
What if only math.round(2.5); ?

Swathi said:   1 decade ago
I have satisfied with this question and answers.
(1)

Post your comments here:

Your comments will be displayed after verification.