精确计算n的阶乘

精确计算的思想是用数组保存每一位的数字,这就要求需要事先估算最高位,防止出现爆站现象。模拟乘法,就是小学学的乘法。输出别忘了加上换行

#include<stdio.h>
#include<iostream>
using namespace std;
int main()
{
	int num;                          //计算数字
	while (scanf("%d", &num) != EOF)
	{
	    int result[100005]; //保存结果
	    int buf;            //当前位置的数字
	    int height = 1;     //最高为为
	    for(int i = 1; i <= num; i++)
        {

            int res = 0;    //进位
            for(int j = 0; j < height; j++)
            {
                buf = result[j] * i + res;    //计算当前位置
                result[j] = buf % 10;
                res = buf / 10;         //计算进位
            }
            while(res)                  //计算最高位
            {
                result[height++] = res % 10;
                res /= 10;
            }
        }
            for(int i = height - 1; i >= 0; i--)
                cout<<result[i];
            printf("\n");
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/fuzekun/article/details/82987681