This week's book giveaway is in the Jython/Python forum.
We're giving away four copies of Murach's Python Programming and have Michael Urban and Joel Murach on-line!
See this thread for details.
Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Dividing floats  RSS feed

 
John Lynn
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why would:

print out "2.0" instead of "2.6" ??
 
Rob Ross
Bartender
Posts: 2205
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
a and b are both ints, so the division that is performed is an integer division, in which only the integer portion of the result is kept. After the integer division, the result is converted to a float and assigned to the left-hand-side variable.
If you want to use floating-point division, you can make your arguments (a&b) floats, or manually cast one of the operands to a float, like this:

float f = (float)a/b;
This will cause a to be converted to a float, and thus so will b, and the division will be a floating-point operation and maintain the non-integer portion of the result.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!