TdarknessT
2021-05-18 23:13
采纳率: 100%
浏览 39

用c语言编写下列代码

编写下列表达式前20项和的程序,要求自定义函数实现 e^x=1+x+x²/2!+x³/3!+……

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • benbenli 2021-05-19 00:00
    已采纳
    int main()
    {
        int n = 20;
        int i;
        double x;
        double factorial = 1;
        double power = 1;
        double sum = 1;
        
        printf("Please enter x: ");
        scanf("%lf", &x);
        
        for (i = 1; i < n; ++i)
        {
            factorial *= i;
            power *= x;
            sum += power / factorial;
            printf("i = %d, power = %lf, factoria = %lf, item = %lf. sum = %lf\n", i, power, factorial, power / factorial, sum);
        }
        
        printf("%lf\n", sum);
        
        return 0;
    }
    
    // Output
    Please enter x: 4
    i = 1, power = 4.000000, factoria = 1.000000, item = 4.000000. sum = 5.000000
    i = 2, power = 16.000000, factoria = 2.000000, item = 8.000000. sum = 13.000000
    i = 3, power = 64.000000, factoria = 6.000000, item = 10.666667. sum = 23.666667
    i = 4, power = 256.000000, factoria = 24.000000, item = 10.666667. sum = 34.333333
    i = 5, power = 1024.000000, factoria = 120.000000, item = 8.533333. sum = 42.866667
    i = 6, power = 4096.000000, factoria = 720.000000, item = 5.688889. sum = 48.555556
    i = 7, power = 16384.000000, factoria = 5040.000000, item = 3.250794. sum = 51.806349
    i = 8, power = 65536.000000, factoria = 40320.000000, item = 1.625397. sum = 53.431746
    i = 9, power = 262144.000000, factoria = 362880.000000, item = 0.722399. sum = 54.154145
    i = 10, power = 1048576.000000, factoria = 3628800.000000, item = 0.288959. sum = 54.443104
    i = 11, power = 4194304.000000, factoria = 39916800.000000, item = 0.105076. sum = 54.548180
    i = 12, power = 16777216.000000, factoria = 479001600.000000, item = 0.035025. sum = 54.583206
    i = 13, power = 67108864.000000, factoria = 6227020800.000000, item = 0.010777. sum = 54.593983
    i = 14, power = 268435456.000000, factoria = 87178291200.000000, item = 0.003079. sum = 54.597062
    i = 15, power = 1073741824.000000, factoria = 1307674368000.000000, item = 0.000821. sum = 54.597883
    i = 16, power = 4294967296.000000, factoria = 20922789888000.000000, item = 0.000205. sum = 54.598088
    i = 17, power = 17179869184.000000, factoria = 355687428096000.000000, item = 0.000048. sum = 54.598136
    i = 18, power = 68719476736.000000, factoria = 6402373705728000.000000, item = 0.000011. sum = 54.598147
    i = 19, power = 274877906944.000000, factoria = 121645100408832000.000000, item = 0.000002. sum = 54.598149
    54.598149
    

    added debug to show the calculation clearly

    打赏 评论
  • xiaoliangtongzhi 2021-05-18 23:31

    #include void main() { double x,ex,t,n; int i; scanf("%lf",&x); n=ex=t=1; for ( i=1;i<20;i++ ) { t*=x; n*=i; ex+=t/n; } printf("%.3lf\n",ex); } 这个代码可以帮助你。

    打赏 评论

相关推荐 更多相似问题