-4

Why in c++ double doesn't work if I write:

int a, b;
double c;

a=11;
b=2;
c=a/b;

right answer according to me should be 5,5 but it writes just 5 anyone knows how to fix this?

abelenky
  • 63,815
  • 23
  • 109
  • 159
  • 6
    because int/int = int, so do a*1./b, or (double)a/b, or C++ way `static_cast(a)/b;` – Creris Feb 03 '15 at 19:29
  • Check this topic: http://stackoverflow.com/questions/28256829/c-program-why-does-this-array-have-this-output/28256899 – myaut Feb 03 '15 at 19:30
  • 8
    C++ doesn't look at the type of the result when it does the calculation, it performs the calculation based on the types of the operands (which are both integer) and *then* converts the result. You fix it by making sure one of the operands *isn't* int. – Mark Ransom Feb 03 '15 at 19:30

2 Answers2

3

A division of an int by another int yields an int. This occurs before the quotient is assigned to the double variable.

To fix this, cast at least one of the int values to a double. In other words, change this:

c=a/b;

to this:

c = static_cast<double>(a) / b;
Spire
  • 685
  • 6
  • 15
0

a must be double too, or float

double a,b,c;

That'll work

ForceBru
  • 43,482
  • 10
  • 63
  • 98