Scala Power Calculator: Calculate the Power of a Number
Write a Scala function to calculate the power of a number.
Sample Solution:
Scala Code:
object PowerCalculator {
def calculatePower(base: Double, exponent: Int): Double = {
var result = 1.0
var i = 0
while (i < exponent) {
result *= base
i += 1
}
result
}
def main(args: Array[String]): Unit = {
val base = 3.0
val exponent = 4
val result = calculatePower(base, exponent)
println(s"The result of $base raised to the power of $exponent is: $result")
}
}
Sample Output:
The result of 3.0 raised to the power of 4 is: 81.0
Scala Code Editor :
Previous: Find the maximum element.
Next: Check if a number is even.
What is the difficulty level of this exercise?
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics