急 用C++求20! 高手帮下忙
- 提问者网友:留有余香
- 2021-06-08 12:54
- 五星知识达人网友:青尢
- 2021-06-08 13:26
#include <string>
using namespace std;
int main(void)
{
int n=20;
int m = 1, sum = 0;
for(int i = 1; i <= n; ++i)
{
m *= i;
}
cout << "20! " << m<< endl;
return 0;
}
- 1楼网友:深街酒徒
- 2021-06-08 16:45
代码,但是方法没有错,但是由于类型的限制,类型也是有范围限制的,一旦超出范围就会出错!
这个程序我试过,最多只能求到 16!,要求到20!的要另寻新径咯!可能 游戏王 的方法可以借鉴!^_^
#include<iostream.h> long fn(long n); void main() { long n; cout<<"请输入所求 n阶乘的数 n(输入0 时,结束输入):"<<endl; while(cin>>n) { if(n<0) cout<<"输入非法!请输入正整数..."<<endl; cout<<"n 的阶乘是:"<<fn(n)<<endl; } } long fn(long n) { int s=1; for(int i=1;i<=n;i++) s=s*i; return s; }
- 2楼网友:掌灯师
- 2021-06-08 15:33
#include <iostream> using namespace std;
int fun(int n) //递归函数 { if (n==1) return 1; else return fun(n-1)*n; }
int main() { cout<<"20!="<<fun(20)<<endl; return 0; }
- 3楼网友:千杯敬自由
- 2021-06-08 15:14
- 4楼网友:几近狂妄
- 2021-06-08 13:52
#include "stdafx.h" #define N 20 int i; int a[N]={0}; static void factorial(int n) { for(int i=2; i< N; i++) a[i] = 0; //将数组元素初始化 a[0] = 1; //用数组的一项存放计算结果的位数 a[1] = 1; //将第一项赋值为一 for(int j= 2; j <= n; j++) { int i=1; int c = 0; //c表示向高位的进位 for(; i <= a[0]; i++) { a[i] = a[i] * j + c;//将来自低位的计算结果和本位的结果相加 c = a[i] / 10; a[i] = a[i] % 10; } for(; c != 0; i++) { a[i] = c%10; c = c / 10; } a[0] = i - 1; } } int main(int argc, char* argv[]) { int n; char s='y'; while(s=='y') { printf("n! Please input the number n,n<10000:\n"); scanf("%d",&n); factorial(n); for(i=N;i>0;i--) printf("%d",a[i]); printf("\n"); printf("%d\n",a[0]);//输出结果的位数 printf("continue?\n"); s=getchar(); s=getchar(); } }
求其他的大数n!,改#define N 的值即可 |