Finding Square Root in Java: Methods and Examples

Respondido utilizando GPT-4o-mini por Java Q&A Hub

Pregunta:

Introduce Java How To Find the Square Root of a Number and give examples

Respuesta:

In Java, you can find the square root of a number using the Math.sqrt() method, which is part of the java.lang package. This method takes a double value as an argument and returns the square root of that value. If the argument is negative, the method will return NaN (Not a Number).

Syntax

double result = Math.sqrt(double number);

Example 1: Finding the Square Root of a Positive Number

Here’s a simple example that demonstrates how to find the square root of a positive number:

public class SquareRootExample {
    public static void main(String[] args) {
        double number = 25.0;
        double squareRoot = Math.sqrt(number);
        
        System.out.println("The square root of " + number + " is: " + squareRoot);
    }
}

Output:

The square root of 25.0 is: 5.0

Example 2: Finding the Square Root of a Negative Number

If you try to find the square root of a negative number, you will get NaN:

public class SquareRootNegativeExample {
    public static void main(String[] args) {
        double number = -16.0;
        double squareRoot = Math.sqrt(number);
        
        System.out.println("The square root of " + number + " is: " + squareRoot);
    }
}

Output:

The square root of -16.0 is: NaN

Example 3: Finding the Square Root of a Decimal Number

You can also find the square root of decimal numbers:

public class SquareRootDecimalExample {
    public static void main(String[] args) {
        double number = 2.25;
        double squareRoot = Math.sqrt(number);
        
        System.out.println("The square root of " + number + " is: " + squareRoot);
    }
}

Output:

The square root of 2.25 is: 1.5

Example 4: Using User Input

You can also take user input to find the square root of a number:

import java.util.Scanner;

public class SquareRootUserInput {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        System.out.print("Enter a number: ");
        double number = scanner.nextDouble();
        
        double squareRoot = Math.sqrt(number);
        
        if (Double.isNaN(squareRoot)) {
            System.out.println("The square root of " + number + " is: NaN (not a number)");
        } else {
            System.out.println("The square root of " + number + " is: " + squareRoot);
        }
        
        scanner.close();
    }
}

Summary

  • Use Math.sqrt() to find the square root of a number in Java.
  • The method returns NaN for negative inputs.
  • You can work with both integer and decimal values.
  • User input can be handled using the Scanner class for dynamic calculations.

These examples should give you a good understanding of how to find the square root of a number in Java!