Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 为什么计算实际小数字(34+;)的阶乘返回0 int n=Convert.ToInt32(Console.ReadLine()); 整数阶乘=1; 对于(int i=1;i_C#_Console Application - Fatal编程技术网

C# 为什么计算实际小数字(34+;)的阶乘返回0 int n=Convert.ToInt32(Console.ReadLine()); 整数阶乘=1; 对于(int i=1;i

C# 为什么计算实际小数字(34+;)的阶乘返回0 int n=Convert.ToInt32(Console.ReadLine()); 整数阶乘=1; 对于(int i=1;i,c#,console-application,C#,Console Application,您超出了变量可以存储的范围。这实际上是一个阶乘,其增长速度比指数快。尝试使用(max value 2^64=18446744073709551615)而不是int(max value 2^31=2147483647)-ulong p=1,这应该会让您更进一步 如果您需要更进一步,.NET 4及更高版本有,它可以存储任意大的数字。如果您使用.NET 4.0并希望计算1000的阶乘,请尝试使用biginger而不是Int32或Int64甚至UInt64。您的问题陈述“不起作用”这还不足以让我很好地服

您超出了变量可以存储的范围。这实际上是一个阶乘,其增长速度比指数快。尝试使用(max value 2^64=18446744073709551615)而不是int(max value 2^31=2147483647)-
ulong p=1
,这应该会让您更进一步


如果您需要更进一步,.NET 4及更高版本有,它可以存储任意大的数字。

如果您使用.NET 4.0并希望计算1000的阶乘,请尝试使用
biginger
而不是Int32或Int64甚至UInt64。您的问题陈述“不起作用”这还不足以让我很好地服从。 您的代码将类似于:

int n = Convert.ToInt32(Console.ReadLine());
int factorial = 1;

for (int i = 1; i <= n; i++)
{
    factorial *= i;    
}
Console.WriteLine(factorial);
使用系统;
使用系统数字;
命名空间控制台应用程序1
{
班级计划
{
静态void Main()
{
int factorial=Convert.ToInt32(Console.ReadLine());
var结果=计算因子(阶乘);
控制台写入线(结果);
Console.ReadLine();
}
私有静态BigInteger计算因子(int值)
{
BigInteger结果=新的BigInteger(1);

对于(int i=1;i由于大多数编程语言处理整数溢出的方式,您得到了0。如果您在循环中输出每个计算的结果(使用十六进制表示),您可以很容易地看到发生了什么:

int n=Convert.ToInt32(Console.ReadLine());
整数阶乘=1;

对于(int i=1;i@user169654)是的,正如codesparkle在评论中指出的那样,BigInteger可能是一个不错的选择。您必须在项目中添加对
System.Numerics
的引用。+1…关于阶乘的另一个有趣的事实是,由于产品的2^32部分,它将开始返回0。“BigInteger”代码中没有定义,编译器给我错误!我已将其更改为完整控制台应用程序Snnipeti我是初学者。抱歉(:编译器给我错误。“数字”SpaceName中不存在它应该是System.Numerics命名空间。请再次检查它。在上面的示例中,此命名空间拼写正确。我已在我的计算机上运行了该代码,并生成了正确的结果
using System;
using System.Numerics;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main()
        {
            int factorial = Convert.ToInt32(Console.ReadLine());

            var result = CalculateFactorial(factorial);

            Console.WriteLine(result);
            Console.ReadLine();
        }

        private static BigInteger CalculateFactorial(int value)
        {
            BigInteger result = new BigInteger(1);
            for (int i = 1; i <= value; i++)
            {
                result *= i;
            }
            return result;
        }
    }
}
int n = Convert.ToInt32(Console.ReadLine());
int factorial = 1;
for (int i = 1; i <= n; i++)
{
  factorial *= i;
  Console.WriteLine("{0:x}", factorial);
}
Console.WriteLine(factorial);