0

I wrote

double r = 2/3;
cout << "r = " << r << endl;

Then it returns

r = 0

I would like it to show that r = 0.666667 or something like that instead of a 0. Especially I need to use that r = 2/3 to do calculation in my algorithm. How can I fix that?

user398843
  • 159
  • 8
  • Many other questioners have already been told this answer, I'm surprised you didn't see them when you searched before asking, I can only assume the search engine is broken :-) `2 / 3` is *integer* division because the components are integers. Make one of them floating point and you'll get better results: `2.0/3`. – paxdiablo Sep 25 '19 at 04:23
  • [check here](https://stackoverflow.com/questions/37777053/how-to-convert-integer-to-double-implicitly) – BAS Sep 25 '19 at 04:24

1 Answers1

2

Because both 2 and 3 are literals of type int, and integer division yields an integer result in C++. What you did is perform integer division first, then promote the integer result to double.

Instead, you want to cast at least one of the operands to float or double (a fractional floating point-type), then the other operand will be promoted to the same type and the resulting value will also be float or double.

Either of these will work:
double r = 2.0/3.0;
double r = 2.0/3;
double r = 2/3.0;

Violet Giraffe
  • 32,368
  • 48
  • 194
  • 335