I was trying to implement a simple combination function
private int combination(int n, int k)
{
if(n>>1 < k)
k = n - k;
double mul = 1;
for(int i=n+1-k;i<n+1;i++)
mul *= i;
for(int i=k;i>0;i--)
mul /= i;
return (int)mul;
}
When I feed in parameters as combination(33,17)
, it gives me 1166803109, though the correct number should be 1166803110. So I printed out the mul
variable before truncating to int, and it gives me a decimal number: 1.1668031099999998E9, which is confusing to me. By definition it should be a perfect division, why it gives me a decimal?