Header Graphic
Member's Message > How to Perform Modulus Operation on Floating-Point
How to Perform Modulus Operation on Floating-Point
Login  |  Register
Page: 1

rashmi agar
58 posts
Mar 16, 2025
9:35 PM
I need to calculate the c++ float modulus . I know that for integers, the modulus operator % works fine, but it doesn’t seem to work with float or double.

I found fmod() in , and it seems to work:

cpp
Copy
Edit
#include
#include

int main() {
double a = 5.5;
double b = 2.0;

std::cout << "fmod(5.5, 2.0) = " << fmod(a, b) << std::endl;

return 0;
}
Output:

cpp
Copy
Edit
fmod(5.5, 2.0) = 1.5
I also came across remainder(), which gives a different result:

cpp
Copy
Edit
std::cout << "remainder(5.5, 2.0) = " << remainder(a, b) << std::endl;
Output:

Copy
Edit
remainder(5.5, 2.0) = -0.5
This confused me because fmod() and remainder() don’t behave the same way. Can someone explain the difference between them?

Also, is there any way to implement a custom floating-point modulus function that mimics the integer % behavior?


Post a Message



(8192 Characters Left)


Copyright © 2011 SUNeMALL.com All rights reserved.                             Terms of Use    Privacy Policy    Returns Policy    Shipping & Payment    Contact Us    About Us   FAQ