Could anyone tell me why the 1st result is 2 while the 2nd result is 2.5? I mean why the1st one is and integer and the 2nd float | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

Could anyone tell me why the 1st result is 2 while the 2nd result is 2.5? I mean why the1st one is and integer and the 2nd float

#include <iostream> using namespace std; int main() { double result=0.0; double a=0.0; double b=0.0; result=5/2; cout<<"1st result is:"<<result<<endl; cout<<endl; a=5; b=2; result=a/b; cout<<"2nd result is:"<<result<<endl; return 0; }

9th Aug 2017, 8:51 AM
RiGeL
RiGeL - avatar
1 Answer
+ 2
This is because the first result is a division two integers, so result is an integer and you lose the remainder. While for the second result both numbers are floating point numbers​, so the result is floating point and you get 2.5 If the first one was 5.0 / 2.0, then the compiler would treat this as a floating point and would be 2.5 also.
9th Aug 2017, 10:19 AM
Jared Bird
Jared Bird - avatar