In the methods which return doubles the solution multiplies int a by 1.0.
Why is the necessary?
Daniel Whyte
Level 17
X by 1.0
Under discussion
Comments (1)
- Popular
- New
- Old
You must be signed in to leave a comment
Guadalupe Gagnon
28 January 2021, 15:14useful
Because both arguments are ints in that method, if you just divide them you will end up with an int. Say 5 divided by 3, that will equal 1 in integer division because integers can not hold decimal values and just drop them completely (not round to nearest whole number). By multiplying by 1.0, which is a double, you force the compiler to convert 'a' to a double. This is because the computer is not able to do math on variables of different types. With numbers it will take the smaller type and convert it into the larger type so that it can complete the operation. In this case Integer stores values in 32 bits while double stores values in 64 bits. So, in this case, the computer will convert the int into a double then do the operation.
The conversion only happens when a smaller and larger type occur as operands on an operator, and follows the natural mathematical order of operations. So, using the above example:
5 * 1.0 / 3
1) operator * will process first
a) the operand 5 (int) does not match type of operand 1.0 (double)
b) so 5 is converted to a double of 5.0 before the operator processes
c) operator processes, the result is 5.0, a double
2) next the operator / processes
a) the operand from step 1, 5.0 (double), doesn't match the type of operand 3 (int)
b) 3 will be converted to a double of 3.0 before the operator processes
c) operator processes, the result is 1.66666, a double
3) the final result is reached and used as coded (returned from the method in this code)
+3