simonJarr
simonJarr

Reputation: 28

Recursion function; "...has stopped working"

I am trying to make a program that gives a specific sum until some point that I define, here it is:

float sum(int n,float m);

main(void) {
    float a,m=1.0;
    int n;
    scanf_s("%ld", &n);
    a = sum(n, m);
    printf("%f", a);
}

float sum(int n, float m) {
    if ((n/m) < 0.0005) {
        return 0;
    }
    else {
        return n/m + sum(n, m + 2);
    }
}

(Notice that the point I defined is 0.0005) When I give a value bigger or equal to 5, program gives me this error:

...has stopped working

Also, when I increase the defined point to like 0.5, the number of values I can give increases too. Why do you think is this happening and how can I fix it?

Upvotes: 0

Views: 78

Answers (1)

dbush
dbush

Reputation: 225827

The %ld format specifier to scanf_s expects a long int * argument. What you're passing in is a int *. These types are incompatible. Using the wrong format specifier invokes undefined behavior, which in this case manifests as a crash.

The proper format specifier for an int * is %d:

scanf_s("%d", &n);

EDIT:

The crash you're seeing is probably a stack overflow. The sum function will recursively call itself 1000 * n times. I see a similar error under MSVC but at a different limit. You can get around this by going with an iterative solution:

float sum(int n, float m){
  float result = 0;
  while ((n/m) >= 0.0005){
    result += n/m;
    m+=2;
  }
  return result;
}

Upvotes: 1

Related Questions