I just need an explanation as to how the abs method works. Im kind of annoyed that alot of the tasks im doing i have to look to the help section for as not everything has been taught needed to answer the question.
Could someone explain the abs method too me?
Under discussion
Comments (5)
- Popular
- New
- Old
You must be signed in to leave a comment
Damodar Gopagoni
2 March 2020, 07:02
Question : Closest to 10
public static int abs(int a) {
if (a < 0) {
return -a;
} else {
return a;
}
}
this method still returning positive eve though user input is negative. any suggestions on this please
0
horst
12 January 2020, 12:14useful
I agree, there are always some exercises for which you have to do your own research in order to solve it, but I think its still a good mix of easy and challenging tasks.
To your question: Simply put, the absolute value of a number is just the same number without its sign (positive/negative). So, the absolute value of 3 is just 3, whereas the absolute value of -3 is also 3 (positive). While this operation might seem a bit useless at first, it is especially helpful when you want to calculate the concrete "distance" or "difference" between two things. (Like in the "Closest to Ten"-task right here). The distance between 8 and 10 is 2, right? and the difference between 10 and 12 is also 2. A very convenient way to calculate this:
10 - 8 = 2
10 -12 = -2
So the difference between those two is the same amount (2), only with a different sign. Without the absolute value function you would always have to start with the question: is the first number bigger or smaller than the other? Or: Which one of the two numbers is the bigger one? And then subtract the smaller from the bigger (10-8 and 12-10) to get an equal result.
Wouldn't it be great instead if we had a function that simply gets rid of the minus? Then we can compare those two numbers without checking which one is bigger.
To implement the absolute value function yourself, its quite simple as soon as you get it. (And you have just learned about if-else-statements in the CodeGym-course!)
+2
Joshua
19 January 2020, 09:04
Thank you very much horst for that detailed reply. That was an excellent explanation and i now understand the concept! :)
+1
horst
19 January 2020, 21:29
You're very welcome! I'm glad I could help. Happy Coding!
0
Richard Melton
11 January 2020, 22:12useful
think of the levels more as an outline of what you need to learn and how to learn directing you with lots of specific practicals instead of as a full lectured course or text book of answers. Most of what I have been doing I may understand on the surface but I am finding that most of what is helping me is that the level tells me what I need to learn and I can then research it and practice it more. I am still lost on most of it but slowly grasping it the more tasks I complete.
+1