Search code examples
cstringpointersfloating-point-exceptions

Floating Point Exception of my Excercise (C language)


I've just made a program that implements a binomial function (n!/k!*(n-k)!).

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;
}

Solution

  • 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.