【牛刀小試3】e的值(精度為1e-6),牛刀小試1e-6

來源:互聯網
上載者:User

【牛刀小試3】e的值(精度為1e-6),牛刀小試1e-6

【牛刀小試3】e的值(精度為1e-6)

 

主要知識:

1.        函數

2.        階乘

3.        for迴圈

4.        if

5.        break

 

下列公式是求e的運算式:

e= 1+1/1!+1/2!+1/3!+……1/n!

 

[ 程式1 ]

    說明:使用函數求N!,再判斷1.0/N!<=1e-6,如果滿足就退出,反之就繼續。

//e= 1+1/1!+1/2!+1/3!+……1/n!(精度為1e-6時)#include <stdio.h> int main( void ){         inti;         intj;         doublee= 1 ;         doublesum= 1;                 for(i= 1; ; i++ )  //這裡也可以使用while迴圈代替         {                   sum*=i; //每次求值都在上一次的基礎                                     e+=1.0/ sum;                                     if(( 1.0/ sum) <= 1e-6 ) //判斷                   {                            break;  //結束for迴圈                   }         }                 printf("e= %lf\n" , e );            return 0; }


運行結果:

 

 [ 程式2 ]

    說明:使用for語句求N!,再判斷。

#include <stdio.h> int factorial( int n )  //求N!階乘的函數{         intj= 0;         intsum= 1; //必須賦值,且為1                 for(j= 1; j<= n ; j++ )         {                   sum*=j;         }                 returnsum;}  int main( void ){         inti= 0;         doublenum= 0.0;         doublee= 1.0;  //必須賦值。。                 do         {           i++;                     num= 1.0/ factorial( i );                     e+= num;         }while(num> 1e-6 ); //判斷條件                 printf("e= %lf\n", e );            return 0; }

運行結果:

 

 

【指尖的微笑】錯誤在所難免,希望得到大家的指正^-^

轉載時保留原文的連結http://codingit.howbbs.com和http://blog.csdn.net/mirrorsbeyourself

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.