ALGORITHM/문제해결

[JAVA] 절대 값 ( Math.abs() )

안낭우훗 2018. 8. 5. 20:29

/*문제: 13 [절대 값 Math.abs()]
  1) 배열에서 이웃 값과의 차이(절대값)를 모두 더하여 출력하라!
  >java Test
  2) 배열 데이터 예:
  {1, 2, 4, 7, 11, 9}
  3) 출력 예:
  합계: 34
  절대값 합계: 12
  Math.abs(값) => 절대값

 

class Test {

 public static void main(String[] args) throws Exception {

   int[] lists = {1, 2, 4, 7, 11, 9};
   int sum = 0;
   for (int list : lists) {
     sum += list;
   }
   System.out.printf("합계: %d \n", sum);

   sum = 0;
   for (int i = 0; i < lists.length - 1; i++) {
     sum += Math.abs(lists[i] - lists[i + 1]);
   }
   System.out.printf("절대값 합계: %d \n", sum);
  }
}