C语言OJ项目参考(1034) 求值

来源:互联网 发布:python base64 decode 编辑:程序博客网 时间:2024/04/28 16:20

(1034) 求值
Description
求Sn=1!+2!+3!+4!+5!+…+n!之值,其中n是一个数字。
Input
n
Output

Sample Input
5
Sample Output
153
参考解答

#include <stdio.h>int main ( ){    int n, i;    long fact=1, sum=1;    scanf("%d",&n);    for(i=2;i<=n;i++)    {        fact=fact*i;        sum+=fact;    }    printf("%ld", sum);    return 0;}

  本题中未指定n的大小。实际上,当n≥13时,n!就已经超过int型数据的取值范围而溢出。所以,本题中,将fact、sum定义为long型,以解决溢出问题。
  目前在32位的系统中,long型与int都占4个字节。结果是,n≥13时,即使fact、sum定义为long型,溢出在所难免。我在编这道程序时,在我的机器上测试,int型的结果与long型的结果一致。
  神奇的是,在OJ平台上,fact、sum定义为int型为错,当它们为long型时却对了。因为,代码被提交到了服务器,服务器是64位的,long型为8个字节。
  另外,下面的程序是最保险的:

#include <stdio.h>int main ( ){    int n, i;    long long int fact=1, sum=1;    scanf("%d",&n);    for(i=2;i<=n;i++)    {        fact=fact*i;        sum+=fact;    }    printf("%lld", sum);    return 0;}

  这里,将fact、sum定义为long long int型,即使32位系统,当n≥13时,变可以得到正确的解答,这时,输出结果时,格式控制该用%lld。不过,在32位系统上安装的CodeBlocks会给我们出来2个warning,不要理会即是。

0 1
原创粉丝点击