C
C#3y ago
T3CH

Modulus division returning 1 less than it should [Answered]

public static int
CPCalculatePennies(double change)
{
double pennies = change % 5 % 1 % 0.25 % 0.1 % 0.05 / 0.01;
return (int)pennies;
}
public static int
CPCalculatePennies(double change)
{
double pennies = change % 5 % 1 % 0.25 % 0.1 % 0.05 / 0.01;
return (int)pennies;
}
when i assign change, its equal to 0.95. it should return 5, but this is returning 4? shouldnt it be returning 5?
10 Replies
phaseshift
phaseshift3y ago
That's looks like a good way to get hurt by rounding errors
T3CH
T3CHOP3y ago
idk what that means, but im doing this for a compsci project lol its supposed to calculate how many pennies when you input change
phaseshift
phaseshift3y ago
Better learn about why 0.1 is not nice for computers/floating point representation then Advise not using double or float for simple money projects tbh
T3CH
T3CHOP3y ago
yeah but the teacher is telling me to what should i do
phaseshift
phaseshift3y ago
Lol
T3CH
T3CHOP3y ago
im rly new to compsci lol i just did math.round so im gonna assume this works lol so like
Math.Round(double pennies = change % 5 % 1 % 0.25 % 0.1 % 0.05 / 0.01;)
Math.Round(double pennies = change % 5 % 1 % 0.25 % 0.1 % 0.05 / 0.01;)
and it works so like yuhh
phaseshift
phaseshift3y ago
Yeah (int) just truncates
T3CH
T3CHOP3y ago
alr lol
phaseshift
phaseshift3y ago
If you use math. Round with someone's money you go to jail tho lol
Accord
Accord3y ago
✅ This post has been marked as answered!
Want results from more Discord servers?
Add your server