0

Thank you for helping me!

In Microsoft Expression Blend 4 (WPF), I wrote a piece of code below, to control the range of x. The code can be down again and again when I press keys:

            if (e.KeyStates == Keyboard.GetKeyStates(Key.Down))
            {
                x = x + 0.2;

                if (x == 0.8)
                {
                    x = x - 0.2;
                }
                TB.Text= Convert.ToString(-x*5);
            }   

            else if (e.KeyStates == Keyboard.GetKeyStates(Key.Up))
            {
                x = x - 0.2;    

                if (x == -1)
                {
                    x = x + 0.2;
                }
                TB.Text= Convert.ToString(-x*5);
            }

However, when I press up and down randomly, I found thet in the TB(a textbox), the 0 doesn't appear, and is replaced by 2.775 or -2.77. How come?

Thank you!

Lu Huang
  • 25
  • 5
  • `double` can not represent `0.2` or `0.8` exactly. More operations you do => more possible error is accumulated due to rounding. – user4003407 Apr 21 '19 at 15:32
  • As @PetSerAl said. There is error across every decimal place in a floating point number. Decimal (a fixed point data type), however, does not rely on floating point numbers and will not have precision errors across every decimal digit. Their decimal positions work like two separate integers. The disadvantage with decimal is that the decimal point is fixed and can't be as large. To specify a decimal, add a D: 0.2D – TamusJRoyce Apr 21 '19 at 18:48
  • https://stackoverflow.com/questions/1089018/why-cant-decimal-numbers-be-represented-exactly-in-binary/1089026#1089026 – TamusJRoyce Apr 21 '19 at 18:55

0 Answers0