Home >Backend Development >C++ >Power function in C/C++

Power function in C/C++

PHPz
PHPzforward
2023-09-02 21:25:031481browse

Power function in C/C++

Power function is used to calculate the power of the given number.

The pow function find the value of a raised to the power b i.e. ab.

Syntax

double pow(double a , double b)

It accepts double integers as input and gives double integers as output. Its pow() function is defined in the math.h package.

If you pass an integer to the power function, the function converts it to a double data type. But there is a problem here, sometimes this conversion may store it as a lower double precision number. For example, if we pass 3 and convert it to 2.99, then the square is 8.99940001, which converts to 8. But this is a mistake, although it rarely happens, but to eliminate this error, add 0.25 to it.

Sample code

#include <stdio.h>
#include <math.h>
int main() {
   double x = 6.1, y = 2;
   double result = pow(x, y);
   printf("%f raised to the power of %f is %f \n" ,x,y, result );
   // Taking integers
   int a = 5 , b = 2;
   int square = pow(a,b);
   printf("%d raised to the power of %d is %d \n", a,b, square );
   return 0;
}

Output

6.100000 raised to the power of 2.000000 is 37.210000
5 raised to the power of 2 is 25

The above is the detailed content of Power function in C/C++. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete

Related articles

See more