Hi! My solution worked, so I'm not able to post it here.
However, I still don't understand one thing:
Why does "((double)b/100) * a;" work and "(double) (b / 100) * a;" doesn't?
Thanks! :)
Casting in the percentage part
Resolved
Comments (5)
- Popular
- New
- Old
You must be signed in to leave a comment
Gellert Varga
29 April 2020, 21:23solution
Hi!
To understand a concrete problem, it is always better if you would send an exact code.
Is your question this? :
Output:
1.3
0.0
and why are they not equals?
The answer is: Java Operator Precedence Table.
If you have several operators in one expressing, then they have a rigorously fixed order of execution.
means "type cast" operation.
See this table:
http://www.cs.bilkent.edu.tr/~guvenir/courses/CS101/op_precedence.html
and you will see the "type cast" is higher than "division". It means: the "type cast" operation will be executed before division. (But you can influence the order of execution, with using parentheses.)
d1: the "type cast" is stronger than dividing. So the "type cast" is the first:
It changes the number 10 to 10.0!
And after the dividing: 10.0/100 = 0.1.
And finally: 0.1*13= 1.3.
d2: as you can see in the table, the parentheses are the top most strong operation.
So, the first: b/100.
b = an int, (=10).
int/int = rounded int:
10/100 = 0!
In the parentheses we get the zero as result.
Second: the "type cast". It changes the number 0 to 0.0!
Third: multiplication.
0.0*13=0. +7
Misiu
29 April 2020, 22:26
Wow. What an explanation!
Admiring...
0
Gellert Varga
29 April 2020, 23:04
:) Thanks!
0
Henrique
30 April 2020, 20:48
Wunderschön! That was a very good explanation. Thanks!
0
Gellert Varga
30 April 2020, 21:05
You're welcome!:)
0