• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Math.round (from Poddar exam)

 
Leverager of our synergies
Posts: 10065
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
from Poddar exam (http://members.theglobe.com/apoddar/questions.html)
Q25. What is the output of following
{
float f4 = -5.5f;
float f5 = 5.5f;
float f6 = -5.49f;
float f7 = 5.49f;
System.out.println("Round f4 is " + Math.round(f4));
System.out.println("Round f5 is " + Math.round(f5));
System.out.println("Round f6 is " + Math.round(f6));
System.out.println("Round f7 is " + Math.round(f7));
}
a)Round f4 is -6
Round f5 is 6
Round f6 is -5
Round f7 is 5
b)Round f4 is -5
Round f5 is 6
Round f6 is -5
Round f7 is 5
Answer: b
My question: Math.round(-5.5f) does yield �5, but is it correct result (from mathematical point of view?), I forgot...
 
Ranch Hand
Posts: 167
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Look at it this way, 5.5 is 0.5 away from being 6.0. That is the starting point for 5.x to be rounded to 6.0. Now -5.5 is only 0.5 away from being -5.0, hence it is the starting point (inclusively) for -5.x to be rounded to -5.0.
Negtives are a bit confusing, and I hope this helps.
 
Ranch Hand
Posts: 59
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
Note that given a float variable f,
Math.round(f) returns the value of
(int)Math.floor(f + 0.5f)
and given a double variable d,
Math.round(d) returns
(long)Math.floor(d + 0.5)
Hope this helps

Originally posted by Mapraputa Is:
from Poddar exam
My question: Math.round(-5.5f) does yield �5, but is it correct result (from mathematical point of view?), I forgot...


 
reply
    Bookmark Topic Watch Topic
  • New Topic