fpiro07
fpiro07

Reputation: 917

For loop doesn't increment the counter 'i'

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?

Upvotes: 1

Views: 3062

Answers (2)

Joost
Joost

Reputation: 4134

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:

double n = 1.3243;
for (int i = 0; long(n*10) % 10 != 0; i++, n *= 10) {   
}
printf("%d\n", i);

GGC gives me a loop.cpp:10: error: name lookup of ‘i’ changed for new ISO ‘for’ scoping error.

The following would fix that (notice how the for-loop does not need curly brackets if it's empty):

double n = 1.3243;
int i;
for (i = 0; long(n*10) % 10 != 0; i++, n *= 10);
printf("%d\n", i);

Using GCC 4.2.1, this gives me the output of 4

But 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:

double n = 1.3243;
if (n == (int)n) {
    // do stuff
}

This fixes the error presented by src: 1.01 is said to have decimals, like it should. The loop solution (wrongly) returns i=0 for this float.

The comparison n == (int)n returns 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.

Upvotes: 8

Cereal_Killer
Cereal_Killer

Reputation: 324

your code is working fine. i =0 , n = 1.3243 .. i =1 , n = 13.243 .. i =2 , n = 123.43 .. i =3 , n = 1234.3 and then terminate if you declare "i" outside the for loop you will get it.

Upvotes: 1

Related Questions