Go Tutorials

Go Programs

Go Compute the Power of a Number


Go Compute the Power of a Number

In this tutorial, we will learn how to compute the power of a number in Go. We will cover the basic concept of exponentiation and implement a function to perform the calculation.


What is Exponentiation

Exponentiation is a mathematical operation that involves raising a base number to the power of an exponent. For example, 2 raised to the power of 3 is 23 = 8.


Syntax

The syntax to compute the power of a number in Go is:

import (
    "fmt"
    "math"
)

func power(base float64, exponent float64) float64 {
    return math.Pow(base, exponent)
}


Computing the power of a number

We can create a function to compute the power of a given base and exponent using the math.Pow function.

For example,

  1. Import the fmt and math packages.
  2. Define a function named power that takes two parameters base and exponent of type float64.
  3. Use the math.Pow function to raise the base to the power of the exponent.
  4. Return the result.
  5. In the main function, call the power function with sample values and print the result.

Go Program

package main

import (
    "fmt"
    "math"
)

func power(base float64, exponent float64) float64 {
    return math.Pow(base, exponent)
}

func main() {
    // Sample values
    base := 2.0
    exponent := 3.0

    // Compute the power
    result := power(base, exponent)

    // Print the result
    fmt.Printf("%.2f raised to the power of %.2f is %.2f\n", base, exponent, result)
}

Output

2.00 raised to the power of 3.00 is 8.00