开发者

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                      
    {
        stati开发者_开发技巧c 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)));
            }
        }
    }
}


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.


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);


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜