I wrote a C program to calculate the number of ways to choose k objects from n distinct objects using functions.
#include<stdio.h>
long f(int a)
{
if(a==1||a==0)return(0);
else return(a*f(a-1));
}
int combination(int N,int K)
{
long int NF,KF,NMKF;
NF=f(N);
KF=f(K);
NMKF=f(N-K);
return(NF/(KF*NMKF));
}
int main()
{
int n,k;
scanf("%d%d",&n,&k);
combination(n,k);
}
But the compiler shows following error message
floating point exception (core dumped)
How to avoid it?
The problem is in this line
if(a==1||a==0)return(0);
It should be
if(a==1||a==0)return(1);
While calculating factorial, n*(n-1)*(n-2)...*(2)*(1). Notice in the end, we multiply by 1 and not zero. multiplying with 0 would make the factorial 0. And later when you are performing division, the 0 comes in the denominator, and floating point exception is occurring. That's why your program is giving error.
For cases when factorial of 0 is needed. Then also this would work, because factorial of 0 is 1 and not 0.. Check this out.
Two problems:
if(a==1||a==0) you should return 1, not return 0. Because 1!=1, 0!=1.choose k objects from n distinct objects. But You should add param checking in order to not occur the n<k. If we input n=2, k=3.The program will go to error. It is bad!
I hope this can help you.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With