SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Stuart Reges, Marty Stepp
Chapter:
Introduction To Parameters And Objects
Exercise:
Exercises
Question:9 | ISBN:9780136091813 | Edition: 2

Question

Write a method called distance that accepts four integer coordinates x1, y1, x2, and y2 as parameters and computes the distance between points (x1, y1) and (x2, y2) on the Cartesian plane. The equation for the distance is:

 

For example, the call of distance(1, 0, 4, 4) would return 5.0 and the call of distance(10, 2, 3, 5) would return 14.7648230602334.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

Program:

public class Ch03Ex09
{
	public static void main(String[] args)
	{
		double res1 = distance(1, 0, 4, 4);
		double res2 = distance(10, 2, 3, 5);
		
		System.out.println("distance(1, 0, 4, 4): " + res1);
		System.out.println("distance(10, 2, 3, 5): " + res2);
	}

	public static double distance(int x1, int y1, int x2, int y2)
	{
		return Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
	}
}

Output:

distance(1, 0, 4, 4): 5.0
distance(10, 2, 3, 5): 7.615773105863909

 

0 0

Discussions

Post the discussion to improve the above solution.