469,946 Members | 1,897 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,946 developers. It's quick & easy.

Strange for loop

1
Hello guys, I got a strange problem when using for loop.

For example, the following code

for ($j = 0.0; $j <= 2; $j+=0.2) {
print $j, " ";
}

gives
0 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8 2 ,
which is normal since the loop is executed 11 times as expected.

However, the following code

for ($j = 0.0; $j <= 3; $j+=0.2) {
print $j, " ";
}

gives
0 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8 2 2.2 2.4 2.6 2.8 ,
where the loop is executed only 15 times instead of expected 16 times!

I can't figure out why, any help is appreciated, thanks!




:confused: :confused:
Nov 3 '05 #1
1 1517
for ($j = 0.0; $j <= 3; $j+=0.2) {
print $j, " ";
}
First of all, use "." (dot) in stead of "," (comma) for string concat.
Second, you're using floating point variables. Read a bit about them here:
http://www.php.net/manual/en/language.types.float.php

There's a pretty pink warning box which clearly says never to compare floating point numbers for equality (directly or indirectly, for example using ($i < $j) || ($i > $j) in stead of ($i != $j) is STILL wrong).
Dec 6 '07 #2

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

4 posts views Thread by hall | last post: by
2 posts views Thread by Alex | last post: by
20 posts views Thread by SpreadTooThin | last post: by
4 posts views Thread by | last post: by
11 posts views Thread by VijaKhara | last post: by
3 posts views Thread by Rinaldo | last post: by
6 posts views Thread by markus.litz | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.