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.
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.
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 int
s and returns an int
. In order to use the double
version, which returns a double
, at least one of the int
s must be explicitly casted to a double
.
c = a/(double)b;
Here it is:
a) Dividing two int
s 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 int
s, 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With