Truncating 1 and 0 and returning as a double
I'm having trouble with the Cars, Assemble exercise on the C# path on Exercism. I'm calculating the success rate based on the speed parameter and no matter how I round or truncate, whenever I try to return 0 or 1, my code only returns 0.9000000000002.
14 Replies
Welcome to floating point rounding errors
0.9 cannot be represented in binary, the closest number is 0.9000000000002
you also have a bug - your conditions are a bit off
if speed is greater than or equal to 1, or speed is lower than or equal to 4..
that is true for all numbers
So I should change it to speed > 0 and speed < 4
what does
||
mean in C#?I thought it meant or?
it does
lets take some numbers as an example thou
-50
, is this above 1 or below 4? yes it is
353214
, is this above 1 or below 4? yes it is
0
, is this above 1 or below 4? yes it is
see my point? 🙂Oh... Lol Im dumb. That should fix it
well, yes and no
because of how your code is written, it checks all the cases, and potentially "overwrites" the former answer
it would be better to
return
once you know what case you are in
in fact, your entire method can actually be written as..
I think I had it set up like that because I was having trouble with the floating points
I was trying to log things to find the problem
what problem?
as ZZZZZZ explained, a float/double simply can't represent 0.9
The problem that was fixed by switching from || to &&
right
debugging should help with that
But I switched from a direct return to a variable so that I had something to log.
right