double n = 1.3243;
for (int i = 0; long(n*10) % 10 != 0; i++, n *= 10) {
}
I’ve written this code in order to understand whether a number has a decimal part or not.
At the end of the loop ‘i’ should be 4 but for some reason the counter doesn’t increment.
Except for the fact that you may not like my solution, do you have any suggestions?
At the end of your loop, the i-variable does no longer exist. You’re declaring it inside the function scope. This results in not being able to access it outside the loop. If you do something like:
GGC gives me a
loop.cpp:10: error: name lookup of ‘i’ changed for new ISO ‘for’ scopingerror.The following would fix that (notice how the for-loop does not need curly brackets if it’s empty):
Using GCC 4.2.1, this gives me the output of
4But the loop you presented has an inconvenient bug, when testing for decimal numbers. As src remarked in his comment, a zero in the decimals cancels any decimals behind it. The loop simply breaks off as soon as it finds a zero value, but there could be more decimals following. Depending on the type of floats you’re dealing with, this could be quite a problem.
Do note: The most common solution is the following comparison:
This fixes the error presented by src:
1.01is said to have decimals, like it should. The loop solution (wrongly) returnsi=0for this float.The comparison
n == (int)nreturns true when your float does not have any decimal parts.As H2CO3 mentioned, testing the decimals of a float-point number is not 100% definite, as floating point rounding might give you a slightly different answer than you’re expecting. It works in the general case, though, so you’ll have to see for yourself if it fits the problem you’re solving.