-2

here is my code example, my question is how to to let the output not to pass 1.0, and match the requirement in "while()"

using System;
                    
public class Program
{
    public static void Main()
    {
        double count = (double)0.0;
        while(count < (double)1.0)
        {
            count = count + (double)0.1;
            Console.WriteLine("{0:R}", count);
        }
    }
}

result:

0.1
0.2
0.30000000000000004
0.4
0.5
0.6
0.7
0.79999999999999993
0.89999999999999991
0.99999999999999989
1.0999999999999999

How to let the code not pass 1.0? (code is in C#)

Tamias
  • 1
  • 2
  • 2
    Why are you using floating point numbers if you require precision? Floating points are _estimates_. In addition, `1.0` is already a double literal, `(double)1.0` is redundant. – gunr2171 Oct 12 '22 at 03:35
  • 1
    Since floating point values can only exactly represent values in base 2. So `0.1d` is *exactly* `0.1000000000000000055511151231257827021181583404541015625`. The last 2 iterations of your loop count will be *exactly*; `0.99999999999999988897769753748434595763683319091796875`, `1.0999999999999998667732370449812151491641998291015625`. The only result that is not a lie is `0.5`. – Jeremy Lakeman Oct 12 '22 at 04:12
  • Adding to what Jeremy said: doubles are imprecise in this way for the same that 1/3 can't be represented accurately in base 10. – ProgrammingLlama Oct 12 '22 at 04:24

1 Answers1

0

You are adding to 'count' after you are checking within the while loop. This is the solution I suggest:

using System;
                    
public class Program
{
    public static void Main()
    {
        double count = (double)0.1;
        while(count < 1.0)
        {
            Console.WriteLine("{0:R}", count);
            count = count + (double)0.1;
        }
    }
}

As you see, I simply switched the timing of the print function and started 'count' at 0.1.