stupid severe issue loop !

Isawyou

New member
Joined
Sep 13, 2020
Messages
1
Programming Experience
5-10
wtf is hapening ?
C#:
for(float i=-5.0f ; i<5.0f ; i+=0.1f)
   Console.WriteLine(i+"\n");
          
// with while
float r=-5.0f;
while (r < 5.0f)
{
  Console.WriteLine(r+"\n");;
  r += 0.1f;
}
//output at -4.5

//-4,9
//-4,8
//-4,7
//-4,6
//-4,5
//-4,400001 <--- this is bullshit makes me angry
 
Last edited by a moderator:
If you don't want to be affected (as much) by such rounding errors, consider using decimal instead of float or double.
 
Control the number of digits by formatting the string:
C#:
Console.WriteLine(i.ToString("n1"));
same with interpolated string:
C#:
Console.WriteLine($"{i:n1}");
 
My question is; what are you doing that you need to be precise enough to use a float?

Why not use doubles or int?
 
Last edited:
Doubles show the rounding error faster...
Screenshot_1.png
 
My guess is the OP might be doing something similar to control the precision of an accelerator in a car or vehicle for example sake. In such case, a float would be the best type to use. But if the OP is trying to do something more simplistic, they might just be using the wrong type. It would be helpful to know what they are actually trying to achieve first.
 
Back
Top Bottom