The fmod() function in C computes the floating-point remainder of the division of two numbers. It is part of the math library <math.h> in C and <cmath> in C++.
fmod() in C
The fmod() function returns the remainder of the division of two floating-point numbers. It is particularly useful when dealing with periodic functions, angles, or any scenario where the remainder after division is required.
Syntax of fmod() in C
double fmod(double x, double y);
Parameters
The method accepts the following parameters:
- x: The dividend, a floating-point number.
- y: The divisor, a floating-point number.
Return Value
The fmod() function returns the remainder of the division x / y as a double. The result has the same sign as the dividend x.
Examples of fmod() Function in C
Example 1
The below program illustrates how to calculate the remainder of the division of two given numbers using the fmod(x, y) function in C:
C++
// C Program to calculate the remainder using fmod() function
#include <math.h>
#include <stdio.h>
int main()
{
// Initialize variables to take the input from the user
// and store the results
double x, y, remainder;
// Take the input from the user
printf("Enter the dividend: ");
scanf("%lf", &x);
printf("Enter the divisor: ");
scanf("%lf", &y);
// Calculate the remainder of the division of x by y
remainder = fmod(x, y);
// Print the remainder
printf("The remainder of %.2lf divided by %.2lf is: %.2lf\n", x, y, remainder);
return 0;
}
Output
Enter the dividend: 7.5
Enter the divisor: 2.3
The remainder of 7.50 divided by 2.30 is: 0.60
Time Complexity: O(1)
Auxiliary Space: O(1)
Example 2
The below program illustrates how to find the remainder for different data types in C.
C++
// C program to calculate the remainder of different data
// types in C using fmod() function
#include <math.h>
#include <stdio.h>
int main()
{
// Initialize variables of different data types
double x1 = 10.5, y1 = 5.5;
float x2 = 10.5f, y2 = 5.5f;
long double x3 = 10.5l, y3 = 5.5l;
// Calculate the remainder using the appropriate fmod
// function for each data type
// fmod function for double
double result1 = fmod(x1, y1);
// fmodf function for float
float result2 = fmodf(x2, y2);
// fmodl function for long double
long double result3 = fmodl(x3, y3);
// Print the results
printf("The remainder of %.2f divided by %.2f is %.2f\n", x1, y1, result1);
printf("The remainder of %.2f divided by %.2f is %.2f\n", x2, y2, result2);
printf("The remainder of %.2Lf divided by %.2Lf is %.2Lf\n", x3, y3, result3);
return 0;
}
OutputThe remainder of 10.50 divided by 5.50 is 5.00
The remainder of 10.50 divided by 5.50 is 5.00
The remainder of 10.50 divided by 5.50 is 5.00
Time Complexity: O(1)
Auxiliary Space: O(1)
Conclusion
The fmod() function is essential when you need to obtain the remainder of a floating-point division. It ensures precision in calculations involving periodic values, such as angles in trigonometry.