Search code examples
c#factorial

Factorial task is incorrectly outputting zero


I'm having a problem in the dry run of a program. I'm not getting why my program is giving 0 in the output. Here is my code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Task_8_Set_III
{
    class Program                      
    {
        static void Main(string[] args)
        {
            int i = 3;
            int c = i / fact(i);
            Console.WriteLine("Factorial is : " + c);
            Console.ReadLine();
        }
        static int fact(int value)
        {
            if (value ==1)
            {
                return 1;
            }
            else
            {
                return (value * (fact(value - 1)));
            }
        }
    }
}

Solution

  • You're dividing integer variables. You're dividing 3 by 6, which gets rounded down to the next integer, which is zero.

    Use the type 'double' instead of 'int' to get the value you're probably looking for.