How to make paired work right? FROM#

Here is the code:

static void Main(string[] args) { int xd2 = 5; for (double xd = (double)xd2; xd <= 6; xd += 0.01) { Console.WriteLine(xd); } } 

and here is the conclusion: enter image description here

I want to keep adding 0.01 (as you can see on the screen, sometimes it happens that adds 0.99999) Thanks

+2
source share
4 answers

Use decimal if you want to maintain such precision.

Floating-point types cannot represent certain values ​​exactly. I suggest reading What every computer scientist needs to know about floating point arithmetic for a detailed explanation.

 decimal xd2 = 5m; for (decimal xd = xd2; xd <= 6m; xd += 0.01m) { Console.WriteLine(xd); } 
+14
source

Not. Here's how doubles work ... try using decimal substitution

  int xd2 = 5; for (decimal xd = (decimal)xd2; xd <= 6; xd += 0.01M) { Console.WriteLine(xd); } 

if you want to stick to doubles, but use only two decimal places ...

 int xd2 = 5; for (double xd = (double)xd2; xd <= 6; xd += 0.01) { Console.WriteLine(Math.Round(xd,2)); } 
+5
source

This is because double is a float pointer, and this arithmetic is inaccurate. Instead, you can use a decimal point, for example:

  static void Main(string[] args) { int xd2 = 5; for (decimal xd = (decimal)xd2; xd <= 6; xd += 0.01M) { Console.WriteLine(xd); } Console.ReadLine(); } 

See also this article: Double-precision Issues in .NET

+2
source

If possible, you should always use absolute instead of iterative calculations to get rid of these rounding errors:

 public static void Main(string[] args) { int xd2 = 5; for (int i = 0; i < 100; ++i) { Console.WriteLine(xd2 + i * 0.01); } } 
+1
source

Source: https://habr.com/ru/post/918530/


All Articles