C语言中的因子 [英] Factorial in C family languages

查看:360
本文介绍了C语言中的因子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试在C ++中创建一个阶乘函数,我发现大于10的输入不能正确计算。我试过C#,但我面临着同样的问题。

I've been trying to make a factorial function in C++, and I just found that inputs which are greater than 10 are not calculated correctly. I tried C# but I faced the same problem.

使用此递归函数:

   int Factorial(int Number) {
        if (Number == 0) return 1;
        return Number * Factorial(Number - 1);
    }

对于大数字,程序返回0,错误计算,我的意思是结果不同于我在Windows计算器。

The program returns 0 for large numbers, and even small inputs such 15 or 16 are wrongly calculated, I mean the result differs from what I get in windows calculator.

推荐答案

这是因为阶乘是大数字,不适合 int 变量。它溢出。如果使用 unsigned long long 而不是 int ,您可以计算更大的阶乘。

This is because factorials are big numbers and the don't fit in an int variable. It overflows. If You use unsigned long long instead of int, You can compute greater factorials.

如果结果不需要精确,你也可以使用double。

If the result doesn't need to be precise, You can use double as well. In the other case, You can implement the multiplication on arrays and You can compute as big factorials as You want.

在C / C ++中,我推荐使用 GMP库

In C/C++, I recommend the GMP library

由于您要求C系列语言:Java有 BigInteger 类型也是有用的。

And because you asked for C family languages: Java has a BigInteger type which is also useful.

这篇关于C语言中的因子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆