因子任务输出错误

Abi*_*bid -2 c# factorial

我在一个程序的干运行中遇到了问题.我不明白为什么我的程序在输出中给出0.这是我的代码:

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)));
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Lee*_*Lee 8

这是因为你正在进行整数除法 - 将一个int除以另一个int的结果是一个int - 因为i / Factorial(i)小于1(对于i> 2),结果被截断为0.你可以通过转换分子和除数来解决这个问题.加倍:

double c = (double)i / (double)fact(i);
Run Code Online (Sandbox Code Playgroud)

编辑:对于i = 1,你有1/1,整数除法为1,没有截断.同样的事情发生在i = 2:(2/Fact(2))2/2 = 1.