Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this for loop stop before reaching the intended value?

for($i=0;$i<=2;$i+=0.1){
    echo  $i."<br>";
}

The result I wish is:

0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
1
1.1
1.2
1.3
1.4
1.5
1.6
1.7
1.8
1.9
2

What happens instead is the loop reaches 1.9 and stops. Why?

like image 660
Jelly Avatar asked May 12 '12 03:05

Jelly


People also ask

Why is my for loop going infinite?

This is a silly example, but it's common for infinite loops to accidentally occur. Most of the times, it's because the variables used in the condition are not being updated correctly, or because the looping condition is in error. We print out x, y, and z since these variables appear in the condition.

Does for loop run only when the condition is true?

A for loop works as long as the condition is true. The flow of control, at first comes to the declaration, then checks the condition. If the condition is true, then it executes the statements in the scope of the loop. At last, the control comes to the iterative statements and again checks the condition.

What happens when the loop condition is no longer satisfied?

An infinite loop occurs when the condition in the While statement is not satisfied. The loop will continue to run until you manually end the program. This often causes a computer to lock up and may require the computer be restarted.


1 Answers

Because, it will never achieve floating point == integer

like image 143
bitoshi.n Avatar answered Sep 24 '22 16:09

bitoshi.n