0

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;
}
Spikatrix
  • 20,225
  • 7
  • 37
  • 83
Sylvestol
  • 13
  • 3

4 Answers4

1

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.

Barmar
  • 741,623
  • 53
  • 500
  • 612
0

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.

FtM
  • 126
  • 9
  • 2
    If you want to use the Socratic method, put it in a comment. Asking another question is not an answer. – Barmar Jul 09 '14 at 10:41
  • Yes, you're right, but.. I mean, it's so obvious that the question is intended to be rhetorical, and the problem on that function is evident once you look at it twice. – FtM Jul 09 '14 at 10:42
  • You should still put that in a comment, not an answer. – Barmar Jul 09 '14 at 10:43
  • I edit the answer to contain the full solution.. Just a moment – FtM Jul 09 '14 at 10:44
0

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

rock321987
  • 10,942
  • 1
  • 30
  • 43
0

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.

pdw
  • 8,359
  • 2
  • 29
  • 41