-2

Why when I ever enter decimal places like 5/9 1/2 ... and initialize it as a double or float, when I use the cout I get 0 prints on the screen Here is the code:

#include <iostream>
using namespace std;
int main () {
double n = 5/9;
cout <<n;

return 0;
}

e.g : 5/9 it prints 0 (the answer that I suppose to get is 0.5555556) 1/2 it prints 0 (the answer that I suppose to get 0.5) Why didn't it print like the supposed values? I already know that double and float are used for decimal values but it only prints 0 and nothing more after the point.

Mohamed Magdy
  • 345
  • 3
  • 15
  • The result of an integer division results in `0` and is implicitly converted to float. Hence the result of `0`. – Ron Nov 29 '17 at 11:00

1 Answers1

1

You are dividing two literal integers, so the result truncates to 0 (as the division is less than 1). To have a correct result you should do double n = 5.0/9.0;, so the division is between two float literals.