Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does dividing two int not yield the right value when assigned to double?

People also ask

What happens when you divide an int by a double?

If either operand is a double, you'll get floating point arithmetic. If both operands are ints, you'll get integer arithmetic. 3.5/3 is double/int, so you get a double. 1/12 is int/int, so you get an int.

What happens if you divide an int?

when you divide two integers, you get an integer result, and when it tries to implicitly cast it to double, it just fails. double d = num2 / (double)num1; cast at least one of them to double, so the compiler understands that it's fractional division you want.

What happens when you divide two ints in C++?

As with all floating point arithmetic operations, rounding errors may occur. If both of the operands are integers, the division operator performs integer division instead. Integer division drops any fractions and returns an integer value. For example, 7 / 4 = 1 because the fractional portion of the result is dropped.


This is because you are using the integer division version of operator/, which takes 2 ints and returns an int. In order to use the double version, which returns a double, at least one of the ints must be explicitly casted to a double.

c = a/(double)b;

Here it is:

a) Dividing two ints performs integer division always. So the result of a/b in your case can only be an int.

If you want to keep a and b as ints, yet divide them fully, you must cast at least one of them to double: (double)a/b or a/(double)b or (double)a/(double)b.

b) c is a double, so it can accept an int value on assignement: the int is automatically converted to double and assigned to c.

c) Remember that on assignement, the expression to the right of = is computed first (according to rule (a) above, and without regard of the variable to the left of =) and then assigned to the variable to the left of = (according to (b) above). I believe this completes the picture.


With very few exceptions (I can only think of one), C++ determines the entire meaning of an expression (or sub-expression) from the expression itself. What you do with the results of the expression doesn't matter. In your case, in the expression a / b, there's not a double in sight; everything is int. So the compiler uses integer division. Only once it has the result does it consider what to do with it, and convert it to double.


When you divide two integers, the result will be an integer, irrespective of the fact that you store it in a double.