You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

关于求阶乘的C++程序输入大于20时输出不准确的咨询

问题分析与解决:C++阶乘程序输入大于20结果不准确

你的程序在输入大于20时输出结果不准确,核心原因是数据类型溢出。unsigned long int的最大取值为4294967295,而21!的结果是51090942171709440000,远超该类型的存储上限,溢出后数值被截断,导致结果错误。

你的循环逻辑(每次乘p和p-1)本身没有问题,但数据类型的容量不足以承载大数值阶乘。

解决方案

  • 改用更大的基础整数类型:将unsigned long int替换为unsigned long long,它的最大取值为18446744073709551615,能正确计算到20!,但21及以上的阶乘仍会溢出。修改后的代码如下:
#include <iostream>
using namespace std;
int main()
{
    unsigned int i,p;
    unsigned long long f=1; // 更换为更大的类型
    cout<<"Enter Number  : "<<endl;
    cin>>i;
    for (p=i;p>1;p-=2){
        f=f*p*(p-1);
    }
    cout<<"Factorial is \n"<<f;
}
  • 实现大数运算:如果需要计算21及以上的阶乘,需要用数组或字符串模拟大整数乘法,示例代码如下:
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

// 字符串大整数乘法
string multiply(string num, int x) {
    string result;
    int carry = 0;
    for (int i = num.size() - 1; i >= 0; i--) {
        int product = (num[i] - '0') * x + carry;
        result.push_back(product % 10 + '0');
        carry = product / 10;
    }
    while (carry) {
        result.push_back(carry % 10 + '0');
        carry /= 10;
    }
    reverse(result.begin(), result.end());
    return result;
}

// 计算阶乘
string factorial(int n) {
    string result = "1";
    for (int i = 2; i <= n; i++) {
        result = multiply(result, i);
    }
    return result;
}

int main() {
    int i;
    cout << "Enter Number  : " << endl;
    cin >> i;
    cout << "Factorial is \n" << factorial(i);
    return 0;
}

这个版本可以处理任意正整数的阶乘,不会出现溢出问题。

内容的提问来源于stack exchange,提问作者johan lenon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 16:15:41