Saturday, June 21, 2014

Java Exercise Nr. 36 (Selections)

Write a program that prompts the user to enter a point ( x , y ) and checks whether the point is within the circle centered at (0 , 0) with radius  10. For example, ( 4 , 5 ) is inside the circle and ( 9 , 9 ) is outside the
circle, as shown in figure below.

Solution:

Formula for calculating the distance between two points:

The value must be equal or less than the radius of the circle in order for a point to be in the circle.


public static void main(String[] args) {
Scanner s = new Scanner(System.in);
double x, y;
double distance;

System.out.print("Enter the value of x and y:");
x = s.nextDouble();
y = s.nextDouble();

distance = Math.pow(Math.pow(x, 2) + Math.pow(y, 2), 0.5);

if(distance <= 10) {
System.out.print("Point (" + x + ", " + y + ") is in the circle.");
} else {
System.out.print("Point (" + x + ", " + y + ") is not in the circle.");
}
}

1 comment:

  1. could someone explain how the "distance = Math.pow(Math.pow(x, 2) + Math.pow(y, 2), 0.5);" part of the code works, I don't quite understand it.

    ReplyDelete

Author