Home »
C++ programming language
Power functions in C++
C++ power functions: Here, we are going to learn about the functions which are used to calculate the powers in C++.
Submitted by IncludeHelp, on April 26, 2019
Power functions are used to calculate the powers (like, raise to power, square root, cubic root, etc). There are following power functions which are the library functions of cmath header.
- pow() function
- sqrt() function
- cbrt() function
- hypot() function
1) pow() function
pow() function is a library function of cmath header (<math.h> in earlier versions), it is used to find the raise to the power, it accepts two arguments and returns the first argument to the power of the second argument.
Syntax
Syntax of pow() function:
pow(x, y);
2) sqrt() function
sqrt() function is a library function of cmath header (<math.h> in earlier versions), it is used to find the square root of a given number, it accepts a number and returns the square root.
Note: If we provide a negative value, sqrt() function returns a domain error. (-nan).
Syntax
Syntax of sqrt() function:
sqrt(x);
3) cbrt() function
cbrt() function is a library function of cmath header, it is used to find the cubic root of a given number, it accepts a number and returns the cubic root.
Syntax
Syntax of cbrt() function:
cbrt(x);
4) hypot() function
hypot() function is a library function of cmath header, it is used to find the hypotenuse of the given numbers, it accepts two numbers and returns the calculated result of hypotenuse i.e. sqrt(x*x + y*y).
Syntax
Syntax of hypot() function:
hypot(x, y);
C++ program to demonstrate example of power functions
// C++ program to demonstrate example of
// power functions
#include <iostream>
#include <cmath>
using namespace std;
// main() section
int main()
{
float x, y;
float result;
//pow() function
x = 12;
y = 4;
result = pow(x,y);
cout<<x<<" to the power of "<<y<<" is : "<<result;
cout<<endl;
//sqrt() function
x = 2;
result = sqrt(x);
cout<<"square root of "<<x<<" is : "<<result;
cout<<endl;
//cbrt() function
x = 2;
result = cbrt(x);
cout<<"cubic root of "<<x<<" is : "<<result;
cout<<endl;
//hypot() function
x = 2;
y = 3;
result = hypot(x,y);
cout<<"hypotenuse is : "<<result;
cout<<endl;
return 0;
}
Output
12 to the power of 4 is : 20736
square root of 2 is : 1.41421
cubic root of 2 is : 1.25992
hypotenuse is : 3.60555