I don’t really understand the number guesser game, i need help with calculating the absolute value
Hi,
Do you have a link to the lesson ? What language is it ?
The absolute value of something is basically its value irrespective of whether it’s negative or not.
So, for example,
-4 and 4 both have an absolute value of 4.
-32 and 32 are both 32.
Most languages have a built-in function that will work out the absolute value (eg, abs() in python), but it’s fairly straightforward to do.
if num is less than zero multiply by minus 1 otherwise the number is positive, so do nothing.
e.g. (python)
if num < 0:
num = num * -1
Hope that helps
it’s JavaScript…
link to the challenge: https://www.codecademy.com/paths/front-end-engineer-career-path/tracks/fecp-22-javascript-syntax-part-i/modules/wdcp-22-number-guesser/projects/number-guesser-independent-practice
Hi,
So, in the project you are looking for which number, the users or the PCs. is closest to the secret guess.
This means you want to know how large the difference is, but not whether it’s positive or negative - i.e. its absolute value.
For example, if the target number was 5, and the guesses were 2 and 8.
8 - 5 = 3
2 - 5 = -3
They are the same distance from 5, but not the same result.
If we then take the absolute value of the result we get 3 for both.
To do that in JavaScript we can wrap the sum in the Math function, abs;
pcDist = Math.abs(pcGuess - target)
userDist = Math.abs(userGuess - target)
Now you can directly compare pcDist and userDist to find which was closer.
(you probably have different variable names)
Hope that helps.
wow!! that clarified things… thank you very much
This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.