views:

122

answers:

4

I'm having problem in the dry run of a program.. I'm not getting why my program is giving 0 in the output.. please help.. 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)));
            }
        }
    }
}
+8  A: 

It's because you're doing integer division - the result of dividing one int by another is an int - since i / Factorial(i) is less than 1 (for i > 2), the result gets truncated to 0. You can fix this by converting the numerator and divisor to doubles:

double c = (double)i / (double)fact(i);

EDIT: for i = 1, you have 1/1 which is 1 for integer division and no truncation occurs. The same thing happens for i = 2: (2/Fact(2)) 2/2 = 1.

Lee
but when i initialize i=1; it gives 1.. why is this so then?
Abid
@Abid: because 1/fact(1) is 1/1 is 1.
Martinho Fernandes
@Abid: Look at Danthan's comment to your question. 1 factorial is 1, but 3 factorial is 6. Since you're dividing the original number by its factorial, you get 3/6. While that arithmetically is .5, the fractional portion gets truncated in integer division, leaving you with 0.
Adam Robinson
+2  A: 

As Lee said, you're doing integer division in line

int c = i / fact(i);

Change c & i to decimal or double...

double c = (double)i / fact(i);

Charles Bretana
thanks alot..!! that helped! :))))
Abid
+1  A: 

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.

Aaron
Why is this the accepted answer when a more complete (and higher-voted) answer was given three minutes prior?
Adam Robinson
A: 

but when i initialize i=1; it gives 1.. why is this so then?

Abid
This should be a comment not an answer.
Yuriy Faktorovich