2

I wrote a program in c#

        static void Main(string[] args)
    {
        float   c = 1.111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111F;
        double  d = 1.111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111F;
        Console.WriteLine(d);
        Console.WriteLine(c);

        Console.WriteLine(c == d);
        Console.Read();
    }

output is:

1.11111116409302
1.111111
True

So,Question:
why is its output is true
Please help me understand this,Thanks!

2

1 Answer 1

3

When you do the first assignment, the constant is truncated to fit the float. When you do the second assignment, the float-precision literal 1.1111...11F is converted to double. Since c contains the value of the 1.1111...11F literal, initialization of d is equivalent to

double d = ((double)c);

Both assignments change the precision of the constant from the literal, but they change it differently. That is why you see different printouts in the first two WriteLines.

When you compare c and d, the value with the lower precision, i.e. c, is converted to the type with the higher precision, i.e. to double. That is the same conversion as the conversion that has been performed when you assigned the 1.1111...11F literal to variable d, so the values compare the same in the == operation. In other words, when you do this

Console.WriteLine(c == d);

the compiler does this:

Console.WriteLine(((double)c) == d);

That is why the comparison returns true.

1
  • thanks for helping me understand how compiler works Dec 20, 2013 at 5:36

Not the answer you're looking for? Browse other questions tagged or ask your own question.