Search code examples
c#factorial

I'm doing a factorial c# program, but after the second attempt, it starts to miscalculate


int num, i, fatorial = 1;
char resposta;
    
do
{    
    Console.WriteLine("Informe um numero e veja o seu fatorial: ");
    num = int.Parse(Console.ReadLine());

    for(i=1; i <= num; i++)
    {
        fatorial *= i;
    }
    Console.WriteLine("O fatorial de "+num+" é "+fatorial);
    Console.WriteLine("Calcular outro número (s/n)?");
    resposta = char.Parse(Console.ReadLine());
} while(resposta !='n');

The first time the works fine, but if a try again, it miscalculates.


Solution

  • You need to reset factorial each loop, otherwise it holds the value from the last loop.

    Add:

    do
        {    
            factorial = 1; // re-initialize every loop
            Console.WriteLine("Informe um numero e veja o seu fatorial: ");
            num = int.Parse(Console.ReadLine());