- Hello friends! We often encounter problems related to maths and to deal with it is such a cumbersome task but thankfully not in C programming language as it offers rich set of library functions to deal with mathematical problems.
- In this post I will explain some of the basic and most frequently used math handling functions. Note that all the math related functions are written inside <math.h> header file so don’t forget to include it in our program to utilize math functions.
floor( ):
- It returns the nearest integer value which is less than or equal to the floating point argument passed to this function.
Syntax:
double floor ( double x );
Example:
#include <stdio.h>
#include <math.h>
void main()
{
float i=5.1, j=5.9, k=-5.4, l=-6.9;
printf("floor of %f is %f\n", i, floor(i));
printf("floor of %f is %f\n", j, floor(j));
printf("floor of %f is %f\n", k, floor(k));
printf("floor of %f is %f\n", l, floor(l));
}
abs( ):
- It returns the absolute value of an integer. The absolute value of a number is always positive. Only integer values are supported in C.
Syntax:
int abs ( int n )
Example:
#include <stdio.h>
#include <stdlib.h>
void main()
{
int m = abs(200); // m is assigned to 200
int n = abs(-400); // n is assigned to -400
printf("Absolute value of m = %d\n", m);
printf("Absolute value of n = %d \n",n);
}
Output:
Absolute value of m = 200 Absolute value of n = 400
round( ):
- It returns the nearest integer value of the float/double/long double argument passed to this function.
- If decimal value is from ”.1 to .5″, it returns integer value less than the argument.
- If decimal value is from “.6 to .9″, it returns the integer value greater than the argument.
Syntax:
Double round(double a);
float roundf (float a);
long double roundl (long double a);
Example:
#include <stdio.h>
#include <math.h>
void main()
{
float i=5.4, j=5.6;
printf("round of %f is %f\n", i, round(i));
printf("round of %f is %f\n", j, round(j));
}
Output:
round of 5.400000 is 5.000000
round of 5.600000 is 6.000000
pow():
- It is used to find the power of the given number.
Syntax:
double pow (double base, double exponent);
Example:
#include <stdio.h>
#include <math.h>
void main()
{
printf ("2 power 4 = %f\n", pow (2.0, 4.0) );
printf ("5 power 3 = %f\n", pow (5, 3) );
}
Output:
2 power 4 = 16.000000
5 power 3 = 125.000000
sqrt( ):
- It is used to find the square root of the given number.
Syntax:
double sqrt (double x);
Example:
#include <stdio.h>
#include <math.h>
void main()
{
printf ("sqrt of 16 = %f\n", sqrt (16) );
printf ("sqrt of 2 = %f\n", sqrt (2) );
}
Output:
sqrt of 16 = 4.000000
sqrt of 2 = 1.414214