This week's book giveaway is in the JavaScript forum.
We're giving away four copies of Svelte and Sapper in Action and have Mark Volkmann on-line!
See this thread for details.
Win a copy of Svelte and Sapper in Action this week in the JavaScript forum!
  • 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Bear Bibeault
  • Junilu Lacar
Sheriffs:
  • Jeanne Boyarsky
  • Tim Cooke
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • salvin francis
  • Frits Walraven
Bartenders:
  • Scott Selikoff
  • Piet Souris
  • Carey Brown

Math.round and casting

 
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public class RoundTest{
public static void main(String args[]){
double d = 3.5;
int i = (int)d; // This becomes 3?
i *= (int)Math.round(d); // This becomes 12?
i *= (int)Math.round(d-6); // What happens here?
System.out.println(i); //prints -24
}
}
I thought this would print -48, can anyone explain why this prints -24? Thanks in advance
 
Tim Murphy
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
By the way this is from JQPlus Mock Test 6.
Question ID: 953841415240
 
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
the 3.5 is put into an int which gives you 3 which is * by round of 3.5 which is 4. so 3*4=12
The d-6 gives you -2.5 which is rounded to -2 therefore the 12*-2 gives you -24 which is you answer
 
Tim Murphy
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Brent,
Were I went wrong was thinking 3.5-6 = -3.5, doh.
And then I though rounding -3.5 made -4.0, but it doesn't! This is important it would equal -3.0
 
    Bookmark Topic Watch Topic
  • New Topic