What is the pow() function in Swift?
Overview
The pow() function calculates the value of a
The figure below shows the mathematical representation of the pow() function:
Note: We need to import
Foundationin our code to use thepow()function. We can import it like this:import Foundation.
Syntax
Let's view the syntax of the function:
pow(baseNumber, exponent)
Function syntax
Parameters
The pow() function requires two parameters:
- A base number.
- An exponent number.
Return value
The pow() returns the value of the base number raised to the exponent number.
Code example
The code below shows the use of the pow() function in Swift:
import Swiftimport Foundation//positive: baseNumber positive: exponentprint ("The value of pow(2.0,3.0) : ",pow(2.0,3.0));//positive: baseNumber negative: exponentprint ("The value of pow(0.25,-2.0) : ",pow(0.25,-2.0));//negative: baseNumber positive: exponentprint ("The value of pow(-10.0,2.0) : ",pow(-10.0,2.0));//negative: baseNumber negative: exponentprint ("The value of pow(-0.5,-1.0) : ",pow(-0.5,-1.0));
Code explanation
- Line 2: We add the
Foundationheader required for thepow()function.
- Line 5: We calculate the positive base number raised to the positive exponent using
pow(). - Line 8: We calculate the positive base number raised to the negative exponent using
pow(). - Line 11: We calculate the negative base number raised to the positive exponent using
pow(). - Line 14: We calculate the negative base number raised to the negative exponent using
pow().