"; } ?> this code prints the...">

For loop not executed for float values

I have a for loop as below

<?php 

 for($i=0;$i<=10;$i+0.4){

 echo $i."<br>";
 }

 ?>

this code prints the value i to 9.6, not 10.

why does it return i = 10. Finally

+5
source share
7 answers

due to the representation of floating point numbers for machines - http://en.wikipedia.org/wiki/Floating_point

I would recommend using integer indexes for loops

+3
source

Use +=to enlarge it, not just a plus. As of now, this is an endless cycle for me.

Edit: For some reason, PHP is not working properly with different types in loops.

This below should work

for($i=0;$i<=100;$i+=4){
   echo $i/10."<br>";
 }

Here var_dump

int(0)

float(0.4)

float(0.8)

float(1.2)

float(1.6)

int(2)

float(2.4)

float(2.8)

float(3.2)

float(3.6)

int(4)

float(4.4)

float(4.8)

float(5.2)

float(5.6)

int(6)

float(6.4)

float(6.8)

float(7.2)

float(7.6)

int(8)

float(8.4)

float(8.8)

float(9.2)

float(9.6)

int(10)

, , - PHP,

+2

FLOAT ( < =).

:

 for($i=0; $i<=100; $i+=4){
     echo ($i/10)."<br>";
 }
+2

:

<?php 

 for($i=0;$i<=100;$i += 4){

 echo ($i/10)."<br>";
 }

 ?>

: http://codepad.org/CxvzEUeq

+1

, , , ...

<?php

   for($i=0; round($i,1) <= 10; $i += 0.4){
      echo $i."<br/>";
   }

?>
+1

<?php

for($i=0;$i<10;$i+0.4){

echo $i."<br>";

}

?>

u <= 10, 10, remove = sign, 9!

+1

epsilon, float.

$epsilon=0.000001; //a very small number

for($i=0; $i<10 or abs($i-10)<$epsilon; $i+=0.4){
   echo $i."<br>";
}
0

All Articles