Problem with Fibonacci Sequence Calculation

Asked

Viewed 58 times

-1

I am doing an exercise that is to return the Fibonacci Sequence in C language up to a certain number informed by the user. The problem is that the program instead of calculating up to that number, it performs one more sequence calculation. For example, I typed that I want up to number 50 and it calculates up to 55, if I type that I want up to number 10 it calculates up to 13.

void calculoFibonacci(int);

int main(){

  int numeroFinal;

  printf("Digite ate que numero voce deseja calcular : ");
  scanf("%d",&numeroFinal);

  calculoFibonacci(numeroFinal);

 system("pause");
 return 0;
}

void calculoFibonacci(int num){
   int antecessor = 0, sucessor = 1, auxiliar;

   for (auxiliar = 0; auxiliar <= num;){
      auxiliar = antecessor + sucessor;
      printf("%d \n",auxiliar);
      antecessor = sucessor;
     sucessor = auxiliar;
}
}
  • 1

    It’s the same problem as this https://answall.com/a/449482/101. So you were happy there because you got the result, but you didn’t learn how to do it. This hinders your evolution. It would not be interesting to try to find the solution to truly learn instead of getting the result?

  • I’ve tried to put one more count in the question, but it returns the same result as what I’m doing.

  • I did (auxiliary = 1; auxiliary <= num; auxiliary = auxiliary + predecessor ){ //auxiliary = auxiliary + predecessor; printf("%d n", auxiliary); predecessor = successor; successor = auxiliary; }

  • I found the result, but I don’t know what the difference is between what I was doing before, and what I’m doing now.

1 answer

-1

basically the problem is in the last execution of the for, as its pro condition is ending depends on a calculation and not only the increment of one by one, it may occur of the calculation to overcome the condition, for example:

for(auxiliar = 0; 34 <= 50;) //verdade
    auxiliar = 21 + 34;
    printf("55");

that is to stop the loop if it is larger q o num, then uses a if(...) break

    while(auxiliar <= num)
    {
        antecessor = sucessor;
        sucessor = auxiliar;
        auxiliar = antecessor + sucessor;
        if(auxiliar > num) break;
        printf("%d \n", auxiliar);

    }
  • I took the test and it’s not working

  • took the wrong part aq, malz (and strange n have worked that, aq tested with 2 compitalador and function)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.