Java program to enter any number and calculate its square root
ADVERTISEMENTS
Java program to enter any number and calculate its square root.
There are you will learn how to find the square root of any number in the Java language.
Formula:
r = n^(1/2)
where:
r = root
n = number
There are two ways to implement these formulae:
- By using the Math.sqrt() function
- Second, by using the Math.pow() function
1. By using the Math.sqrt() function
// Java program to calculate the square root of a number
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter any number to find the square root::\n");
double n = in.nextDouble();
double r;
// n = number
// r = root
/* Calculate square root of number */
r = (double)Math.sqrt(n);
// Output
System.out.println("\nSquare root of:: " + n + " = " + r + "\n");
}
}
Output:
Enter any number to find the square root::
25
Square root of:: 25.0 = 5.0
2. By using the Math.pow() function
// Java program to calculate the square root of a number using the Math.pow() function
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter any number to find the square root::\n");
double n = in.nextDouble();
double r;
// n = number
// r = root
/* Calculate square root of number */
r = (double)Math.pow(n, 0.5);
// Output
System.out.println("\nSquare root of:: " + n + " = " + r + "\n");
}
}
Output:
Enter any number to find the square root::
25
Square root of:: 25.0 = 5.0