본문 바로가기
Project/Study | etc

JAVA의 정석 3판 - 두 점 사이 거리 계산

by 코젼 2022. 6. 26.
728x90
반응형

📝문제 1

💾소스코드

// 두 점의 거리를 계산하는 getDistance()를 완성하시오.
public class Exercise6_6 {
	// 두 점(x, y)와 (x1, y1) 간의 거리를 구한다.
	static double getDistance(int x, int y, int x1, int y1) {
//		(1) 알맞은 코드를 넣어 완성하시오.
		double distance;
//		
		distance = Math.sqrt(Math.pow(x1-x, 2) + Math.pow(y1-y, 2)); 
		return distance;
	}
	
	public static void main(String[] args) {
		System.out.println(getDistance(1,1,2,2));
	}
}

📝문제 2

💾소스코드

// 클래스메소드 -> 인스턴스메소드로 정의하기

class MyPoint  {
	int x;
	int y;
	
	MyPoint(int x, int y) {
		this.x = x;
		this.y = y;
	}
	
	double getDistance(int a, int b) {
		double distance;
		distance = Math.pow(a-this.x, 2) + Math.pow(b-this.y, 2);
		return Math.sqrt(distance);
	}
	
//	(1) 인스턴스메소드 getDistance를 작성하시오.
}

public class Exercise6_7 {
	public static void main(String[] args) {
		MyPoint p = new MyPoint(1,1);
		
		// p와 (2,2)의 거리를 구한다.
		System.out.println(p.getDistance(2,2));
	}
}
728x90
반응형

댓글