Use C language to calculate the power function and exponential function method

  • 2020-04-02 03:16:06
  • OfStack

C pow() function: x to the y
The header file:


#include <math.h>

Pow () function is used to find x to the y (), and its prototype is:


  double pow(double x, double y);

Pow () is used to calculate base x to the y and return the result. Let the return value be ret, then ret = xy.

Situations that can lead to errors:

If the base x is negative and the exponent y is not an integer, a domain error will result. If base x and index y are both 0, domain error may or may not occur. This is related to the implementation of the library. If base x is 0 and exponent y is negative, it may cause domain error or pole error, or it may not. This is related to the implementation of the library. If the return value ret is too large or too small, it will cause a range error.

Error code:

If a domain error occurs, the global errno is set to   EDOM; If a pole error or range error occurs, the global errno is set to ERANGE.

Note that when compiling with GCC, join -lm.

See the following code.


#include <stdio.h>
#include <math.h>
int main ()
{
  printf ("7 ^ 3 = %fn", pow (7.0, 3.0) );
  printf ("4.73 ^ 12 = %fn", pow (4.73, 12.0) );
  printf ("32.01 ^ 1.54 = %fn", pow (32.01, 1.54) );
  return 0;
}

Output results:


7 ^ 3 = 343.000000
4.73 ^ 12 = 125410439.217423
32.01 ^ 1.54 = 208.036691

C language SQRT () function: take the square root of a given value
The header file:


#include <math.h>

SQRT () is used to find the square root of a given value. Its prototype is:


  double sqrt(double x);

X is the value of the square root to be calculated.

If x < 0, will cause a domain error and set the value of the global errno to EDOM.

Returns the square root of x.

Note that when compiling with GCC, join -lm.

Example calculate the square root value of 200.


#include <math.h>
main(){
  double root;
  root = sqrt(200);
  printf("answer is %fn", root);
}

Output results:


answer is 14.142136


Related articles: