mod a floating point

Hey all

So for my homework I'm trying to write a program to find if a user chosen floating point number could actually be stored as an integer. The problem is that I wanted to mod the floating point by one and if no remainder output it can be an integer but that cannot be done. I know I can use fmod to find any remainder but my teacher hasn't used that and I don't know yet if I would be marked down. Any ideas on how this can be done?
You should use fmod(), or possible modf() as they will give you what you want. You may just want to ask your teacher if it is allowed if you are concerned. If you want to implement it manually however, you can cast the floating point value to an integral type to get the integral portion of the number.

However, I would caution you that floating point math is not exact so you may find that even if you have what should be an exactly integral number, you may not actually have one stored that way in memory. You should probably check if the value is within some small range (often called epsilon) of the closest integer value.
Yea I'm waiting for an email reply about if I'd get docked down points. I'm not familiar with epsilon but I will try the fmod. Thanks for the help.

Nice name btw zhuge, possible reference to the sleeping dragon?
1
2
3
4
double d = 7.245;
int integral_part = static_cast<int>(d); // integral_part == 7
double fract_part = d - integral_part; // fract_part is in the realm of 0.245
// what if fract_part was very close to zero? 


MrBond90 wrote:
Nice name btw zhuge, possible reference to the sleeping dragon?

You got it.
Thanks a lot Zhuge, from your example I set up an if statement. if the fraction part is greater than 0 it cannot be stored as integer.

Thanks again for the help. Much appreciated.
You should check if the fractional part is close to zero, rather than if it is just non-zero. For example:
7.0 - 5.0 - 2.0 may not exactly be 0.0
Topic archived. No new replies allowed.