public static int abs(int a) {
if (a < 0) {
return -a;
} else {
return a;
}
}
So I have already completed this task but I was just wondering if someone could explain to me exactly what the statement above is actually doing.
It seems like it's probably something so obvious, but I just can't get my head around it.Can someone explain this to me:
Under discussion
Comments (3)
- Popular
- New
- Old
You must be signed in to leave a comment
Lovekush Pranu
3 May 2020, 10:06
so basically it's supposed to return the absolute value of an integer. the absolute value is the value without any signs. So, basically the magnitude. since the magnitude of a negative number is just number itself( a double negative is positive). It returns positive if it's positive and negative of the negative number if it's negative.
0
Gellert Varga
1 May 2020, 14:15
If you understood everything in the explanation of Msaters, then all right.
Else: make a sign to me and i will try to explain it in other words.
0
Msaters
1 May 2020, 08:55
public mean u can use it everywhere in your program, everything has access to it
static means that ur code will "load" it 1st to your program
int abs(int a) {} - it is sort of function that will return int so some number bcs u have "int abs" if u would habe double abs u would have to return double value
int abs(int a) - this "(int a)" means that while evocation this function u will have to put in there some int
for example
main{
int someInt;
abs(someInt);
}
then u have how your function works it returns "-a" so value of int that u put there multiply -1 when value of a is less than 0 :
iff(a < 0)
return -a;
else
return a;
if a is more than 0 u return a and that's all
0