如何用c++求100的阶乘,在线等,急

如题所述

如果要近似的,可以这么做:

//#include "stdafx.h"//If the vc++6.0, with this line.
#include <iostream>
using namespace std;
int main(int argc,char *argv[]){
    int i;
    double s;
    for(s=i=1;i<101;s*=i++);
    cout << "100! = " << s << endl;
    return 0;
}

如果要精确的,就得麻烦点:

//#include "stdafx.h"//If the vc++6.0, with this line.
#include <iostream>
#include "math.h"
using namespace std;
int main(int argc,char *argv[]){
    int i,j,n,*p;
    double x;
    for(x=0.0,i=2;i<101;x+=log10(i++));
    if((p=new int[x/=6,n=(int)x+(x!=(int)x)])==NULL){
        cout << "Application memory failure...\n";
        return 0;
    }
    for(i=0;i<n;p[i++]=0);
    for(p[n-1]=1,i=2;i<101;i++){
        for(j=0;p[j]==0;j++);
        while(j<n)
            p[j++]*=i;
        for(j--;j>0;j--)
            if(p[j]>999999)
                p[j-1]+=p[j]/1000000,p[j]%=1000000;
    }
    cout << "100! = " << p[0];
    cout.fill('0');
    for(i=1;i<n;cout.width(6),cout << p[i++]);
    delete []p;
    cout << endl;
    return 0;
}

温馨提示:答案为网友推荐,仅供参考
第1个回答  2017-05-24
举例说明算法: 1!+2!+3!+……+n! =1+2*(1+3*(1+4*(1+5(1+......(1+(n-1)*(1+n))......)))) 不过当n=100貌似会溢出。嗯。 因此要实现一个大数乘法的函数,然后就很easy了 #includevoid main(){ long sum; int n=100; sum=n; while(n!=1) { sum+=1追问

求完整代码

第2个回答  2017-05-24
用递归算法,我这是C#语法。
public double calc(int n)
{
if (n == 1)
{
return 1;
}
else
{
return n * calc(n - 1);
}
}

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网