Quote:Original post by Doggan
I think you need to re-read the for loop chapter of your C++ book. Given for(j=0; j < 1; j += 1/40.0f):
1). j is initialized to 0
2). is j < 1? If yes, enter loop. If no, exit loop.
3). execute loop
4). increment j (j += 1 / 20.0f)
5). is j < 1? If yes, enter loop. If no, exit loop.
6). repeat from 3).
In this case, after so many iterations, since j is a float, it is really .99999. It assigns this value to i. It then incrmenets j, j += 1 / 20.0f, which is j = .999999 + .025 = 1.025. The condition, j < 1, is not met. Therefore your loop is not entered, and i remains .999999 (or 1.0).
I haven't looked though your previous two posts, but I just want to let you know that running the program using floats I get
i=0.950000i=1.000000i=1.000000Press any key to continue
But when I change those floats to doubles, and do not change any other code I get:
i=0.950000i=0.975000i=0.975000Press any key to continue
Which is what the OP was saying in the first post. Just throwing that out there - I am not looking at logics or anything like that, just final outputs. Here's the source code that you can test for yourself too if you are interested.
#include <iostream>int main(int argc, char* argv[]){ { printf("First using floats:\n"); float j = 0; float i = 0; for(j = 0; j < 1; j += 1/20.0f) i = j; printf("i=%f\n", i); for(j=0; j < 1; j += 1/40.0f) i = j; printf("i=%f\n", i); j = 0; while(j < 1) { i = j; j += 1/40.0f; } printf("i=%f\n", i); } printf("\n\n"); { printf("Now using doubles:\n"); double j = 0; double i = 0; for(j = 0; j < 1; j += 1/20.0f) i = j; printf("i=%f\n", i); for(j=0; j < 1; j += 1/40.0f) i = j; printf("i=%f\n", i); j = 0; while(j < 1) { i = j; j += 1/40.0f; } printf("i=%f\n", i); } return 0;}
I think the problem was from using floats, but if someone can rewrite the code a different way that does the same thing using floats, and it does produce the correct output, meaning these logics are wrong, then I'd like to see that (I don't have any more time hehe)