Okay, I already solved this task, but I'm a little confused right now.
Generally one example:
Get 5 % of some values:
(100 / 100) * 5 = 5
Or the same in an alternative way:
100 * 0.05 = 5
Both examples above will bring us to the same result (5).
Shouldn't it in Java work the same way, or is this some special thing which has to do with the type double?
I'm getting two different results while using the values mentioned in the task.
Could someone explain this to me?
Thanks!
hidden #10608434
Level 8
What is the difference here?
Gelöst
Kommentare (7)
- Beliebt
- Neu
- Alt
Du musst angemeldet sein, um einen Kommentar schreiben zu können
Artem Divertitto Senior Android Developer bei United Tech
27 April 2020, 10:24
Can you add examples below my message, because I am not fully understand your question
+1
hidden #10608434
27 April 2020, 14:28
I'm sorry for that confusion.
I think it has something to do with the type "double", but I could not find anything about that issue yet.
Okay so here's my example.
1) First System.out result here: This is the first method: 136.0
2) Second System.out result here: This is the second method: 150.96
-> so why is this calculating different here?
150.96 should be fine in both cases.
0
Gellert Varga
26 April 2020, 20:47
It probably has to do with the "double" type.
But I will be able to understand the question exactly only if you copy the code to here, what caused confusion to you. Please write code examples.
+1
hidden #10608434
28 April 2020, 12:15
Thank you, I posted it under the comment of Tiym :)
0
Gellert Varga
28 April 2020, 20:47Lösung
OK, already i get it:)
If you divide one "int" by another "int", the result is also just an "int". Even if you put the result in a variable of type "double"! So:
"888" = int.
"100" = int.
So in line 11:
888/100 = not 8.88! But only a simple 8!
And 8 * 17 is equal to 136.
And then Java puts this 136 into the "double" type variable and then changes to 136.0.
If you have two "int"-s and you want to get an exact dividing result, you must convert at least one "int" to double before the dividing with some trick.
For example, in the case of 888/100:
888 / (100 + 0.0)
(888 + 0.0) / 100
or: 888*0.01.
But if you write the method like this:
in this case, you will also get the wanted correct result because the first line already converts the "weightEarth" "int" to a "double" (888.0). +3
hidden #10608434
29 April 2020, 07:47
Uffff... I thought that it was something like that..
Thank you Gellert! :)
0
Gellert Varga
29 April 2020, 17:27
You're welcome! :)
0