0

I am a bit stuck with this problem:

int a = 5, b = 2;
double c = a / b;
cout << c;

This outputs:

2

Why ?

I can by pass this by using:

double aa = a,
bb = b;
c = aa / bb;

This outputs:

2.5

Help ! :(

rocambille
  • 15,398
  • 12
  • 50
  • 68
user7338118
  • 61
  • 1
  • 3
  • Hint: C++ has different kinds of division. The kind of division done in any given context depends on the types of the two operands, a and b in this case. – Waxrat Dec 24 '16 at 17:24
  • It outputs 2 because b is an integer. The math is done as an integer then converted to a double. – drescherjm Dec 24 '16 at 17:25

2 Answers2

6

In C++ language, any arithmetic operation between two integer values will return an int value. Said differently, the integer division is the Euclidian division. And only then that integer value is casted to a double.

If you want a double operation, you must force the division to operate on double values, either by casting one operand to double, or by multiplying it by 1.0 which is a double constant :

double c = 1.0 * a / b;

or

double c = static_cast<double>(a) / b;
Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
4

You have to at least cast one of the ints to a double:

double c = a/(double)b;
Taufiq Rahman
  • 5,600
  • 2
  • 36
  • 44