一个程序拿出来show show,求n的阶乘保留小数点后16位,在P41.7G下计算100万的阶乘大概是1秒。大家给点意见
ywhbn 2004-12-03 01:54:56 // 在VC++6.0下写的
// 求n的阶乘保留小数点后16位,1.0e+300 进制
// 代码简单就不注释了,在P41.7G,256M内存下计算100万的阶乘大概是1秒
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
// 读浮点数的指数
#define get_exp(p) ( atoi(p + strlen(p) - 3) )
main()
{
time_t
stime,
etime;
unsigned char
pr[50];
unsigned long int
n,
re;
unsigned long int register
i;
double
r;
while(1)
{
printf("input n [<=1.0e+8 , 0 -- exit] :");
scanf("%ld", &n); // n不是整数会死循环
if(!n)
break;
r = 1.0;
re = 0;
// 开始计算
time(&stime);
for(i = 2; i <= n; i++)
{
r = r * i;
if(r >= 1.0e+300)
{
r /= 1.0e+300;
re += 300;
}
}
time(&etime);
sprintf(pr, " %d! = %.20e", n, r);
sprintf(pr+strlen(pr)-3, "%ld", get_exp(pr)+re);
printf(" %s \n ", pr);
printf(" use time: %.4f s\n", difftime(etime, stime));
}
}