Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what's is going wrong with this loop condition? [duplicate]

Tags:

c

Look at the output of this link(scroll down to see the output) to find out what I'm trying to accomplish

The problem is with the for loop on line number 9-11

for(i=0; i<=0.9; i+=0.1){
  printf("%6.1f ",i);
}

I expected this to print values from 0.0 until 0.9 but it stops after printing 0.8, any idea why ??

like image 587
Mudassir Ali Avatar asked Jan 24 '14 20:01

Mudassir Ali


1 Answers

Using float here is source of problem. Instead, do it with an int:

int i;
for(i = 0; i <= 10; i++)
   printf("%6.1f ", (float)(i / 10.0));

Output:

0.0    0.1    0.2    0.3    0.4    0.5    0.6    0.7    0.8    0.9    1.0 
like image 64
Justin Iurman Avatar answered Oct 01 '22 15:10

Justin Iurman