Inversion of "For" does not work correctly. What for?

for (float i = -1; i <= 1; i+=0.1f) { Console.WriteLine(i); } 

These are the results.

 -1 -0.9 -0.8 -0.6999999 -0.5999999 -0.4999999 -0.3999999 -0.2999999 -0.1999999 -0.09999993 7.450581E-08 0.1000001 0.2000001 0.3000001 0.4000001 0.5000001 0.6000001 0.7000001 0.8000001 0.9000002 
+6
source share
6 answers

Since float is not an exact decimal number, but a floating point number. Use decimal instead.

See Wikipedia for reference: Wikipedia

+4
source

Float and double cannot accurately display decimal values. Look at wikipedia how they are implemented.

You can use Decimal instead.

+2
source

Use integers for indexing purposes. And if you need float values โ€‹โ€‹inside the loop, calculate it there:

 for (int i = -10; i <= 10; i++) { Console.WriteLine(i / (float) 10); } 
+1
source

float is a 32-bit floating point number . He cannot accurately represent these values. Here's another mandatory-reading read-only article specifically for .NET: http://csharpindepth.com/Articles/General/FloatingPoint.aspx

0
source

This is because you use floating points. The calculation of floating points is not entirely correct, because your computer uses binary numbers inside, not decimal numbers. Good information on this problem is given here: http://floating-point-gui.de/

0
source

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


All Articles