Standard Math
Double precision floating-point remainder: fmod()
Section titled “Double precision floating-point remainder: fmod()”This function returns the floating-point remainder of the division of x/y. The returned value has the same sign as x.
#include <math.h> /* for fmod() */#include <stdio.h> /* for printf() */
int main(void){ double x = 10.0; double y = 5.1;
double modulus = fmod(x, y);
printf("%lf\n", modulus); /* f is the same as lf. */
return 0;}Output:
4.90000Important: Use this function with care, as it can return unexpected values due to the operation of floating point values.
#include <math.h>#include <stdio.h>
int main(void){ printf("%f\n", fmod(1, 0.1)); printf("%19.17f\n", fmod(1, 0.1)); return 0;}Output:
0.10.09999999999999995Single precision and long double precision floating-point remainder: fmodf(), fmodl()
Section titled “Single precision and long double precision floating-point remainder: fmodf(), fmodl()”These functions returns the floating-point remainder of the division of x/y. The returned value has the same sign as x.
Single Precision:
#include <math.h> /* for fmodf() */#include <stdio.h> /* for printf() */
int main(void){ float x = 10.0; float y = 5.1;
float modulus = fmodf(x, y);
printf("%f\n", modulus); /* lf would do as well as modulus gets promoted to double. */}Output:
4.90000Double Double Precision:
#include <math.h> /* for fmodl() */#include <stdio.h> /* for printf() */
int main(void){ long double x = 10.0; long double y = 5.1;
long double modulus = fmodl(x, y);
printf("%Lf\n", modulus); /* Lf is for long double. */}Output:
4.90000Power functions - pow(), powf(), powl()
Section titled “Power functions - pow(), powf(), powl()”The following example code computes the sum of 1+4(3+3^2+3^3+3^4+…+3^N) series using pow() family of standard math library.
#include <stdio.h>#include <math.h>#include <errno.h>#include <fenv.h>
int main(){ double pwr, sum=0; int i, n;
printf("\n1+4(3+3^2+3^3+3^4+...+3^N)=?\nEnter N:"); scanf("%d",&n); if (n<=0) { printf("Invalid power N=%d", n); return -1; }
for (i=0; i<n+1; i++) { errno = 0; feclearexcept(FE_ALL_EXCEPT); pwr = powl(3,i); if (fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW)) { perror("Math Error"); } sum += i ? pwr : 0; printf("N= %d\tS= %g\n", i, 1+4*sum); }
return 0;}Example Output:
1+4(3+3^2+3^3+3^4+...+3^N)=?Enter N:10N= 0 S= 1N= 1 S= 13N= 2 S= 49N= 3 S= 157N= 4 S= 481N= 5 S= 1453N= 6 S= 4369N= 7 S= 13117N= 8 S= 39361N= 9 S= 118093N= 10 S= 354289Syntax
Section titled “Syntax”- #include <math.h>
- double pow(double x, double y);
- float powf(float x, float y);
- long double powl(long double x, long double y);
Remarks
Section titled “Remarks”- To link with math library use
-lmwith gcc flags.