Home > front end >  How can I deal with compiler error c2660 in recursive function and iterative function?
How can I deal with compiler error c2660 in recursive function and iterative function?

Time:09-22

#include <stdio.h>
double recursive(int n);
double iterative(int n);
int n;
double ans1, ans2;

int main(int n) {
    do {
        printf("input:");
        scanf("%d", &n);
        ans1 = recursive(n);
        ans2 = iterative(n);
        printf("%f", ans1);
        printf("%f", ans2);
    } while (n != 0);
    return 0;
}

double recursive(int n) {
    double result = 0.0;
    result  = (1 / n);
    return recursive(n); 
}

double iterative(int n) {
    int i;
    double result = 0.0;

    for (i = 0; i < n; i  ) {
        result  = (1 / n);
    }

    return result;
}

Visual studio says that recursive function and iterative function has c2660 error. I think I used one arguments each when declaring the function and using the function. How can I fix this problem?

CodePudding user response:

The big issue here is in your recursive function. Every recursive function needs a base case. That is, there must be some condition that, when true, does not cause a recursive call. Also, unless that condition is based on some global variable (which is not a good idea), you need to change the parameter(s) with which you call the function as otherwise it'll just do the same thing every time and never reach the base case. As you have it, no call to recursive will ever return since it always ends up calling itself with the same argument.

Without understanding the purpose of the function, it's difficult to know what that condition should be.

CodePudding user response:

When you declare your main you have only 2 options :

int main(void)
{
  return (0);
}

and

int main(int argc, char **argv)
{
  return (0);
}

because your main function can't be called elswhere than at the start of your program it might be causing a lot of troubles and then you should debug your program to see if you don't have infinite loop. spoiler : there's infinite loops.

  •  Tags:  
  • c
  • Related