Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Modulus of two float or double numbers using C
In C, to find the modulus (remainder) of two floating-point or double numbers, we use the remainder() function from the math library. Unlike the % operator which only works with integers, remainder() handles floating-point arithmetic.
Syntax
double remainder(double x, double y); float remainderf(float x, float y); long double remainderl(long double x, long double y);
Parameters
- x − The numerator (dividend)
- y − The denominator (divisor)
Return Value
Returns the floating-point remainder of x/y. The remainder is calculated as:
remainder(x, y) = x - rquote * y
where rquote is x/y rounded to the nearest integral value.
Example
Note: To use
remainder()function, you need to link with the math library using-lmflag during compilation.
#include <stdio.h>
#include <math.h>
int main() {
double x = 14.5, y = 4.1;
double res = remainder(x, y);
printf("Remainder of %.1lf/%.1lf is: %.1lf<br>", x, y, res);
x = -34.50;
y = 4.0;
res = remainder(x, y);
printf("Remainder of %.1lf/%.1lf is: %.1lf<br>", x, y, res);
x = 7.5;
y = 2.3;
res = remainder(x, y);
printf("Remainder of %.1lf/%.1lf is: %.1lf<br>", x, y, res);
return 0;
}
Remainder of 14.5/4.1 is: -1.9 Remainder of -34.5/4.0 is: 1.5 Remainder of 7.5/2.3 is: 0.6
Key Points
- The
remainder()function uses IEEE remainder, which can return negative values - For division by zero, the function returns NaN (Not a Number)
- The result has the same sign as the numerator in some cases, depending on the rounding
- Use
remainderf()for float andremainderl()for long double types
Conclusion
The remainder() function provides IEEE-compliant floating-point remainder calculation in C. It handles both positive and negative numbers correctly and is the standard way to find modulus of floating-point numbers.
Advertisements
