public static int abs(int a) {
if (a < 0) {
return -a;
} else {
return a;
Андрей
6 уровень
Объясните пожалуйста кто может и на пальцах последовательно как это работает?
Обсуждается
Комментарии (3)
- популярные
- новые
- старые
Для того, чтобы оставить комментарий Вы должны авторизоваться
Vladimir
6 мая 2019, 19:14
hi!У нас есть метод который сравнивает как далеко названные числа от 10 - это displayClosestToTen(),
мы вызываем его 2 раза(по заданию). Затем описываем сам метод, он должен состоять из if, которые сравнивают разницу заданных чисел и 10 и проверяют какая разница является меньше и выводят на экран число которое меньше удалено от 10.
метод abs нужен для того что бы для проверки полученной разницы, если она отрицательная, то метод вернет положительное число для корректного сравнения. Если есть вопросы пиши
0
Yul'ka
6 мая 2019, 11:47
Когда мы передаем в метод abs число (в данном случае а), то программа проверяет на условие и если а меньше 0 (т.е отрицательное), то метод вернет обратное число числу а. ( -5 вернет 5). Если не отрицательное, то его и вернет обратно.
0
hidden #598481
6 мая 2019, 11:45полезный
https://ru.wikipedia.org/wiki/Абсолютная_величина
Это модуль числа. Если число неотрицательное, то функция (метод) возвращает само число. Если число меньше нуля, то он возвращает противоположное ему положительное число.
аргумент (a) → значение (|a|; abs(a)):
3 → 3
1 → 1
0 → 0
-2 → -(-2)=2
-5 → -(-5)=5
+3