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
Since float is not an exact decimal number, but a floating point number. Use decimal instead.
See Wikipedia for reference: Wikipedia
Float and double cannot accurately display decimal values. Look at wikipedia how they are implemented.
You can use Decimal instead.
Decimal
You need to read the following:
What Every Computer Scientist Should Know About Floating Point Numbers
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); }
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
float
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/
Source: https://habr.com/ru/post/893762/More articles:Boost performance in Mongodb with java driver - javaFull code in try / catch block - javarestarting setInterval - javascriptcodeigniter session often ends - codeigniterWhat is the difference between and debug = "false"? - debuggingUse Google Analytics to display data on our web page? - statisticsmultiplication in C without arithmetic operators - cHow to create a synchronized version of Google Guava TreeMultimap - javaUse if condition in ascx file is asp.netdjango plugin wireframe design templates - djangoAll Articles