Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

why 5/2 is not 2.5

Status
Not open for further replies.

enqueoshy

Programmer
Oct 25, 2003
4
MX
#include <iostream.h>
#include <math.h>

int main()
{
double resul;
resul = 5/2;
cout <<"\n resultado : " << resul;
cout <<endl;

return 0;
}

when I copile it shows
/////////////////////////
5 elevado a la 1/3 es

resultado : 2
Press any key to continue
/////////////////////////
 
you are dividing 2 ints and then they get promoted to a double. Make it 5.0/2 and you will get the right answer.

Matt
 
Slightly detailed: in C/C++ integer (integral) division op is not the same operation as a floating point division op. It discards a fractional part of its result. Constants 5 and 2 are integers (by definition). So 5/2 == 2, that's OK.
But 5.0 is a double type constant. The 2nd operand (integer 2) promotes to 1st operand type (double), then we have float point division with result 2.5...
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top