Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Power Function in C/C++
The power function in C is used to calculate the power of a given number. The pow() function finds the value of a raised to the power b i.e., ab.
Syntax
double pow(double base, double exponent);
The pow() function accepts two double values as parameters and returns a double value as output. It is defined in the math.h header file.
If you pass integers to the power function, they are automatically converted to double data type. However, there's a potential precision issue with this conversion. Sometimes floating-point representation might store values slightly differently (e.g., 3 might be stored as 2.99), which could lead to unexpected results in calculations.
Parameters
- base − The base value (double)
- exponent − The power to which the base is raised (double)
Return Value
Returns the result of base raised to the power of exponent as a double value.
Example
Here's an example demonstrating the pow() function with both double and integer values −
#include <stdio.h>
#include <math.h>
int main() {
double x = 6.1, y = 2;
double result = pow(x, y);
printf("%.1f raised to the power of %.0f is %.2f\n", x, y, result);
// Using integers
int a = 5, b = 2;
double square = pow(a, b);
printf("%d raised to the power of %d is %.0f\n", a, b, square);
// More examples
printf("2^3 = %.0f\n", pow(2, 3));
printf("4^0.5 = %.1f\n", pow(4, 0.5));
return 0;
}
6.1 raised to the power of 2 is 37.21 5 raised to the power of 2 is 25 2^3 = 8 4^0.5 = 2.0
Key Points
- Always include
math.hheader when usingpow() - The function returns a double value regardless of input types
- For integer results, cast the return value or use appropriate format specifiers
- Link with math library using
-lmflag during compilation if required
Conclusion
The pow() function in C provides an efficient way to calculate exponential values. It handles both integer and floating-point calculations, making it versatile for mathematical computations requiring power operations.
