Factorial calculation without finishing the program

Asked

Viewed 35 times

0

How would I make this algorithm not to terminate the program and allow me to write other numbers to calculate the factorial? I’ve tried putting one while, or do while, but in no way works, because it goes through the for and the program soon closes..

#include <stdlib.h>
#include <stdio.h>

char resp;
int cont, num;
long fat=1;

main()
{
    printf("Digite um numero para calcular o fatorial: ");
    scanf("%d", &num);

    for(cont=num;cont>1;cont--){
        fat = fat*cont;
    }
    printf("%d! = %d", num, fat);

    printf("\nContinuar [S/N]? ");
    scanf("%c", &resp);

    return 0;
}
  • 1

    The flow of your program is extremely similar to the one presented in the question I suggested as duplicate.

1 answer

1


You just needed to give a space on "%c" of scanf("%c", &resp); leaving this way: scanf(" %c", &resp);, with the do while, the function was thus:

#include <stdlib.h>
#include <stdio.h>



main()
{
  char resp;
    do{
      long fat=1;
      int cont, num;
    printf("Digite um numero para calcular o fatorial: ");

    scanf("%d", &num);

    for(cont=num;cont>1;cont--){
        fat = fat*cont;
    }
    printf("%d! = %d", num, fat);

    printf("\nContinuar [S/N]? ");
    scanf(" %c", &resp);
    }while(resp != 'N');

    return 0;
}

That space is enough for the scanf() understand that it is a new input. We could also use the function fflush(stdin) to avoid this problem (recommend you read about it). A hug!

  • It worked the loop, the problem now is when I type the next number, it’s adding "together", if I type 2 the first time it gets 2 (right), but if I type 2 again, it gets 4 the result.. I think the problem is that it is there inside the while, but there would be no way to get him out, or there would be?

  • 1

    Put the fat=1; right after reading the number, before the factorial calculation loop.

  • I had not touched the global variable, it is not a good practice to fill the code with global variables (but this is not the subject), I updated the code putting your variables (exerto o o Resp) inside the loop

  • Ah, I didn’t know about this variable scheme, I always thought it was necessary to put them up there before starting to develop the algorithm itself, will be useful in the next exercises, thank you very much!

  • 1

    I recommend reading this article: https://www.embarcados.com.br/por-que-evitar-variaveis-global/

Browser other questions tagged

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