This week's book giveaway is in the OCAJP forum.
We're giving away four copies of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) and have Khalid A Mughal & Rolf W Rasmussen on-line!
See this thread for details.
Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

I always get 0 when 1 divided by 3

 
chaohua wang
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, Folks,

I ahve this code
long test = 1/3;
System.out.println( test );

but print reult is 0. How to get result 0.33333?

Thank you!

Chwang
 
Stephen Foy
Ranch Hand
Posts: 143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Long isnt suitable for floating point numbers.

 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1 and 3 are int literals, and int division always truncates. The int result is then widened to type long when it's assigned to the variable "test."

For a floating-point result, at least one of the literals needs to be a float or double. Then the result needs to be assigned to a variable of type float or double.
[ June 01, 2006: Message edited by: marc weber ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic