爱问知识人 爱问教育 医院库

用c 编写程序计算1! 2! ….. n!,其中n单独输入

首页

用c++编写程序计算1!+2!+…..+n!,其中n单独输入


        

提交回答
好评回答
  • 2008-11-13 12:21:00
    #include<iostream>using namespce std;int main(){long n,sum;cout<<"n=?"<<endl;cin>>n;sum=cal(n);cout<<endl<<"sum="<<sum;return 0;}long cal( int n){long i,sum;sum=0;for(i=1;i<=n;i++)sum=sum+falc(i);return sum;}long falc(int n){long ret;if(n==1) ret=1;else  ret=n*falc(n-1);    return ret;}

    w***

    2008-11-13 12:21:00

其他答案

    2008-11-11 19:57:00
  •   #include <iostream。h>//Fa是英语阶乘的开头字母、下面是阶乘函数,实现一个数的阶乘long Fa(int n)  {   int fa=1;      //for循环实现1*2*。。。n   for(int i=1;i<=n;i++)       fa=fa*i;      return fa; //返回fa即n!  }// Add累加函数实现 各个数阶乘的相加即1!+2!。
      。。+n!long Add(int n){ int sum=0; for(int i=1;i<=n;i++) sum=sum+Fa(i);//调用Fa()函数并循环叠加 return sum;//sum的值即是1!+2!。
      。。
      +n! } void main() { long result=0;int n=0; cout<<"please input the number of n"<<endl; cin>>n; result=Add(n);//调用Add函数 cout<<result<<endl; }。

    a***

    2008-11-11 19:57:00

  • 2008-11-11 17:25:00
  •   这个是高精度的,如果n大于等于20的话。肯定就越界了。所以只能用这个高精度。如果你的n很小的话。你就用上面的别人的吧。
      #include <iostream>using namespace std; int main(int argc, char* argv[]) { int carry,n,j; //carry低位超过10向高一位进的数,n阶层数,j数据位数 int a[2000]; //表示数据值的数组 int digit=1; //数据总位数 int temp,i; //temp临时变量,i当前阶层的乘数 cout<<"please enter n:"<<endl; cin>>n; a[0]=1; for(i=2; i<=n; i++) { for(carry=0,j=1; j<=digit; ++j) //向数组中的每一位乘i { temp=a[j-1]*i+carry; //temp保存当前乘的结果加上低位进数 a[j-1]=temp%10; //让数组保存当前位的值(0 ~ 9) carry=temp/10; //需要向高位进carry } while(carry) //当最高位需要进位时,carry保存需要向更高位进的数 { //digit++; a[++digit-1]=carry%10; //总数据位数加1,新最高位保存数据 carry/=10; //新最高位需要向新更高位进的数 } } cout<<"the result is:"<<endl; for(int k=digit; k>=1; --k) cout<<a[k-1]; cout<<endl; return 0; }。

    c***

    2008-11-11 17:25:00

类似问题

换一换

相关推荐

正在加载...
最新问答 推荐信息 热门专题 热点推荐
  • 1-20
  • 21-40
  • 41-60
  • 61-80
  • 81-100
  • 101-120
  • 121-140
  • 141-160
  • 161-180
  • 181-200
  • 1-20
  • 21-40
  • 41-60
  • 61-80
  • 81-100
  • 101-120
  • 121-140
  • 141-160
  • 161-180
  • 181-200
  • 1-20
  • 21-40
  • 41-60
  • 61-80
  • 81-100
  • 101-120
  • 121-140
  • 141-160
  • 161-180
  • 181-200
  • 1-20
  • 21-40
  • 41-60
  • 61-80
  • 81-100
  • 101-120
  • 121-140
  • 141-160
  • 161-180
  • 181-200

热点检索

  • 1-20
  • 21-40
  • 41-60
  • 61-80
  • 81-100
  • 101-120
  • 121-140
  • 141-160
  • 161-180
  • 181-200
返回
顶部
帮助 意见
反馈

确定举报此问题

举报原因(必选):