-4

The below program seems to look like it will run for one time but when i run in Turbo C , the output is nothing. Can any one explain this ?

#include<stdio.h>
int main() 
{
    float x=1.1;
    while(x==1.1)
    {
        printf("%f \n",x);
        x=x-0.1;
    }
    return 0;
}
Amit
  • 45,440
  • 9
  • 78
  • 110
Anisul Huque
  • 71
  • 1
  • 4
  • 8
    Take a look here: http://stackoverflow.com/questions/588004/is-floating-point-math-broken – Inisheer Aug 18 '15 at 07:53
  • This is an often made error: you are comparing a float with a double, and they may be slightly different (IOW, not equal), especially in a non-standard implementation like Turbo C. Note that the last version of Turbo C was released 1989. – Rudy Velthuis Aug 18 '15 at 11:49

2 Answers2

1

By default, floating point numbers are stored as type 'double'. So, a comparison on float and double value is done.

I think,

if(x==1.1f)

it should solve the problem.

And also FLT_EPSILON is the smallest difference between two floating point numbers for them to be same.

if( abs(x-1.1f) <= FLT_EPSILON)

should work

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
sasha48
  • 11
  • 2
0

You can re-write your loop condition as follows-

while((1.0009<x)&&(x<1.10001))

As because x=1.1 in this x is never exact 1.1. At higher decimal places it can have different value.

You can see here at higher decimal places what are values and working example for your code -https://ideone.com/IgrLAY

ameyCU
  • 16,489
  • 2
  • 26
  • 41