C
C#•6mo ago
Cykotech

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.
public static double SuccessRate(int speed)
{
double rate = Math.Round(0.0);

if (speed >=1 || speed <= 4)
{
rate = Math.Round(1.0, 0);
}
if (speed >=5 || speed <=8)
{
rate = Math.Round(0.9, 1);
}
if (speed == 9)
{
rate = Math.Round(0.8, 1);
}
if (speed == 10)
{
rate = Math.Round(0.77, 2);
}

return rate;
}
public static double SuccessRate(int speed)
{
double rate = Math.Round(0.0);

if (speed >=1 || speed <= 4)
{
rate = Math.Round(1.0, 0);
}
if (speed >=5 || speed <=8)
{
rate = Math.Round(0.9, 1);
}
if (speed == 9)
{
rate = Math.Round(0.8, 1);
}
if (speed == 10)
{
rate = Math.Round(0.77, 2);
}

return rate;
}
14 Replies
Angius
Angius•6mo ago
Welcome to floating point rounding errors 0.9 cannot be represented in binary, the closest number is 0.9000000000002
Pobiega
Pobiega•6mo ago
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
Cykotech
CykotechOP•6mo ago
So I should change it to speed > 0 and speed < 4
Pobiega
Pobiega•6mo ago
what does || mean in C#?
Cykotech
CykotechOP•6mo ago
I thought it meant or?
Pobiega
Pobiega•6mo ago
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? 🙂
Cykotech
CykotechOP•6mo ago
Oh... Lol Im dumb. That should fix it
Pobiega
Pobiega•6mo ago
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..
static double SuccessRate(int speed)
{
return speed switch
{
10 => 0.77,
9 => 0.8,
>= 5 and <= 8 => 0.9,
>= 1 => 1,
_ => 0.0
};
}
static double SuccessRate(int speed)
{
return speed switch
{
10 => 0.77,
9 => 0.8,
>= 5 and <= 8 => 0.9,
>= 1 => 1,
_ => 0.0
};
}
Cykotech
CykotechOP•6mo ago
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
Pobiega
Pobiega•6mo ago
what problem? as ZZZZZZ explained, a float/double simply can't represent 0.9
Cykotech
CykotechOP•6mo ago
The problem that was fixed by switching from || to &&
Pobiega
Pobiega•6mo ago
right debugging should help with that
Cykotech
CykotechOP•6mo ago
But I switched from a direct return to a variable so that I had something to log.
Pobiega
Pobiega•6mo ago
right
Want results from more Discord servers?
Add your server