I've just made a program that implements a binomial function (n!/k!*(nk)!)
.
I can compile my program without any problems but when i scanf the 2 int (n and k), it says "Floating Point Exception".
I've tried many ways to fix it but i can't find the problem because i'm not good with c programming :( I'm learning. Someone can help me please? Thank you very much.
#include <stdio.h>
#include <stdlib.h>
int factorial( int n ){
int result;
if( n == 0 ){
result = 0;
} else {
result = n * factorial((n - 1));
}
return result;
}
char *stringa_binomiale(int n, int k){
char *s;
s=malloc(sizeof(char)*20);
int b;
b = factorial(n)/(factorial(k)*factorial(n-k));
sprintf(s,"%i su %i fa %i",n ,k ,b);
return s;
}
int main (void){
int n;
int k;
char *s;
s=malloc(sizeof(char)*20);
printf("n:");
scanf("%i",&n);
printf("k:");
scanf("%i",&k);
s= stringa_binomiale(n,k);
printf("%s \n", stringa_binomiale(n, k));
free(s);
return 0;
}
Your factorial
function always returns 0
for any input, because the base case is wrong. Your base case returns 0
, and when you multiply by this you get 0
.
As a result, you're dividing by 0
in stringa_binomiale
, which causes a floating point exception.
The base case should be n == 1
and it should return 1
.
What could give an FPE? :)
HINT: try to print the outputs of your "factorial" function..
SOLUTION: the "factorial" function always returns 0, and its return is used in a division. n! is 1 if n is 0: change that line and you're fine.
your factorial
function was always returning 0
and thus dividing by 0
was giving floating point exception
the factorial
function should be
int factorial( int n ) {
int result;
if( n == 0 ){
result = 1;
} else {
result = n * factorial((n - 1));
}
return result;
}
and here is the link http://ideone.com/CTKDyX ..
An integer division by zero also gets report as "floating point exception". Don't know why that is, there probably are historical reasons.
If your C compiler is recent enough, you should compile with "-fsanitize=undefined". You'll get runtime messages instead of weird behavior for a lot of C errors, including this one.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.