Skip to main content

How to calculate the square root of a number in Kotlin

How to calculate the square root of a number in Kotlin.

Here's a step-by-step tutorial on how to calculate the square root of a number in Kotlin.

To calculate the square root of a number, you can make use of the sqrt() function in the kotlin.math package. This function returns the square root of a given number.

Here's how you can calculate the square root of a number in Kotlin:

  1. Import the kotlin.math.sqrt function:
import kotlin.math.sqrt
  1. Define the number for which you want to calculate the square root:
val number = 25.0
  1. Calculate the square root using the sqrt() function:
val squareRoot = sqrt(number)
  1. Print the result:
println("The square root of $number is $squareRoot")

Putting it all together, the complete code looks like this:

import kotlin.math.sqrt

fun main() {
val number = 25.0
val squareRoot = sqrt(number)
println("The square root of $number is $squareRoot")
}

When you run this code, it will output:

The square root of 25.0 is 5.0

You can also calculate the square root of a user-inputted number. Here's an example that prompts the user to enter a number and calculates its square root:

import kotlin.math.sqrt
import java.util.Scanner

fun main() {
val scanner = Scanner(System.`in`)
print("Enter a number: ")
val number = scanner.nextDouble()
val squareRoot = sqrt(number)
println("The square root of $number is $squareRoot")
}

In this example, the Scanner class is used to read the user's input from the console. The nextDouble() function is used to read a double value.

That's it! You now know how to calculate the square root of a number in Kotlin.