Reputation: 741
I have this code, which I believe is self-explanatory (although ugly):
public decimal Stat
{
get
{
if (Incorrect == 0)
return 100;
decimal x = (decimal)(Correct / Incorrect) / (decimal)(Correct + Incorrect) * 100;
return x;
}
}
Is there a way to make this code prettier?
Upvotes: 1
Views: 517
Reputation: 186843
You have to use decimal
, not int
arithmetics. The easiest way is to start formula with decimal 100m
:
public decimal Stat
{
get
{
return (Correct + Incorrect == 0)
? 100m
: 100m * Correct / (Correct + Incorrect);
}
}
Upvotes: 4
Reputation: 1031
You don't have to take care of the edge case of Incorrect == 0, because if it holds, then 100 will be returned (100.0 * X / (X+0) equals 100.0)
public decimal Stat
{
get
{
return 100m * Correct / (Correct + Incorrect);
}
}
Upvotes: 2
Reputation: 40838
Two points,
A percentage correct would be Correct * 100m / (Correct + Incorrect)
. You've divided by Incorrect again after this. I don't know why that is but it seems wrong.
The result of integer division is another integer. If Correct is 1 and Incorrect is 4 then the result of Correct / Incorrect
is 0. Always convert to the floating point types before doing division.
I would rewrite this code like so,
public int Total => Correct + Incorrect;
// renamed "Stat"
public decimal PercentageCorrect => (Correct * 100m) / Total;
Total seems like a useful quantity. Let's just make it a property. Renaming "Stat" makes it obvious what it is. Just reading your code, I had to ask what "Stat" was because it was not obvious what you were trying to do.
Upvotes: 1
Reputation: 39152
That should probably be:
public decimal Stat
{
get
{
decimal Total = (decimal)(Correct + Incorrect);
return (decimal)Correct / Total * 100.0M;
}
}
Upvotes: 0