Home > Backend Development > C++ > body text

Power function in C/C++

PHPz
Release: 2023-09-02 21:25:03
forward
1427 people have browsed it

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)
Copy after login

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;
}
Copy after login

Output

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

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!