How to use the math library functions in the C language?
The math library functions in the C language can be used by including the header file
- Mathematical constants:
- PI: The mathematical constant pi can be defined using the macro M_PI.
- E: The natural constant e can be defined using the M_E macro.
- Mathematical functions:
- Parameters and return values of mathematical functions are typically of double precision floating-point type.
- abs(x): Calculate the absolute value of x.
- square root of x: find the square root of x.
- pow(x, y): to calculate the y power of x.
- Calculate the exponentiation of e to the power of x, denoted as exp(x).
- Calculate the natural logarithm of x.
- log10(x): calculating the logarithm of x with base 10.
- sin(x): calculate the sine value of x, where x is given in radians.
- cos(x): calculate the cosine value of x, where x is in radians.
- tan(x): computes the tangent value of x in radians.
- ceil(x): rounding up, returning the smallest integer not less than x.
- floor(x): rounds down to the nearest integer less than or equal to x.
- round(x): round to the nearest integer, returning the closest integer to x.
- random number function
- The random number function needs to be initialized with the srand function to set the seed.
- srand(seed) is used to set the seed for the random number generator, with seed being an integer.
- rand(): Generates a random integer between 0 and RAND_MAX. You can obtain a random number within a specific range by using the modulus operation.
For example, calculating the value of the sine function:
#include <stdio.h>
#include <math.h>
int main() {
double x = 1.0;
double result = sin(x);
printf("sin(%f) = %f\n", x, result);
return 0;
}
This code uses the math library function sin to calculate the sine value of x, and then uses the printf function to output the result.