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.
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?