• 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??

 
Ranch Hand
Posts: 435
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
public class RoundTest
{
public static void main(String args[])
{
double d = 3.5;
int i = (int) d;
i *= (int) Math.round(d);
i *= (int) Math.round(d-6);
System.out.println(i);
}
}
Options :
1)-24
2)-36
3)-48
4)-18
5) none
I tried running the program , it should -24
Can any body explain me ?>
Sonir
 
Bartender
Posts: 2205
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
double d = 3.5;
int i = (int) d;
i *= (int) Math.round(d);
i *= (int) Math.round(d-6);
System.out.println(i);
First, you assign 3.5 to the variable "d". Next, the value in d is cast to an int and stored in the variable i. By casting from a double to an int, you loose the fractional part of the number; it is simply truncated. So i gets the value 3.
Next, the static function round() in the Math class is called with a double argument of value 3.5. This returns the rounded value, which will be 4. (See the JavaDoc for how round() works.) This value (4) is cast to an int, then the "times equal" operator is applied to the operands, and the value 12 is stored in i. (i previously had 3, and we multiplied this by 4).
In the same way, the next line will evaluate to
i*= -2 (d-6 rounds to -2)
Since i currently has 12, 12*-2 = -24, and this is assigned to i.
Rob
And please add those [ CODE] tags! thanks
 
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi, all! I am new here. How to use "Code" tag?
Thank you!
 
Ranch Hand
Posts: 2120
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Just push the button that says code an place your code between the tags that appear
reply
    Bookmark Topic Watch Topic
  • New Topic