In C programming, the standard library provides a set of mathematical functions that perform common mathematical operations. These functions help perform tasks like rounding numbers, calculating powers, trigonometric functions, and more. Let’s explore how to use them!
pow()
— Power FunctionThe pow()
function is used to raise a number to the power of another number. Here's the syntax:
double pow(double base, double exponent);
For example, if we want to calculate 2^3 (2 raised to the power 3), we would use pow(2, 3)
.
pow()
#include#include int main() { double result = pow(2, 3); // 2 raised to the power 3 printf("2 raised to the power 3 is: %.2f\n", result); // Output: 8.00 return 0; }
pow(2, 3)
computes 2 raised to the power of 3, which equals 8. The result is printed with two decimal places.
sqrt()
— Square Root FunctionThe sqrt()
function computes the square root of a number.
double sqrt(double number);
sqrt()
#include#include int main() { double number = 16; double result = sqrt(number); // Square root of 16 printf("The square root of %.0f is: %.2f\n", number, result); // Output: 4.00 return 0; }
sqrt(16)
computes the square root of 16, which equals 4.
fabs()
— Absolute Value FunctionThe fabs()
function returns the absolute value of a number. It is typically used for floating-point numbers.
double fabs(double number);
fabs()
#include#include int main() { double number = -25.5; double result = fabs(number); // Absolute value of -25.5 printf("The absolute value of %.1f is: %.1f\n", number, result); // Output: 25.5 return 0; }
fabs(-25.5)
computes the absolute value of -25.5, which equals 25.5.
fmod()
— Remainder of Division FunctionThe fmod()
function returns the remainder of a division of two floating-point numbers.
double fmod(double x, double y);
fmod()
#include#include int main() { double result = fmod(22.5, 4.0); // 22.5 divided by 4.0 printf("The remainder of 22.5 / 4.0 is: %.2f\n", result); // Output: 2.50 return 0; }
fmod(22.5, 4.0)
computes the remainder when 22.5 is divided by 4.0, which equals 2.5.
sin()
, cos()
, and tan()
— Trigonometric FunctionsThe trigonometric functions in C work with angles in radians. They calculate sine, cosine, and tangent respectively.
sin()
, cos()
, and tan()
to compute the sine, cosine, and tangent of an angle.
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!