用C語言實現:計算1/1-1/2+1/3-1/4+1/5 …… + 1/99 - 1/100 的值。

來源:互聯網
上載者:User

標籤:lag   運行   code   之間   png   system   pow   完成   2-2   

拿到這個題目,我們首先會想到用迴圈來完成。

但並不是每個運算子都是“+”號。

所以,我們在這裡要利用(-1)的i次方來進行“+”“-”號的控制。

再將迴圈變數i當作分母。

到這裡我們對迴圈體的構思就基本ok了。

需要注意的是:這裡的計算結果會以小數表示,所以並不能用int整型來定義變數。

代碼如下:

#include<stdio.h>#include<math.h>int main(){    int i;    float sum=0.0,temp=0.0;    for (i = 1; i <= 100; i++)    {        temp = pow(-1, i + 1);        sum = sum + temp * 1 / i;    }    printf("sum is %f\n", sum);    system("pause");    return 0;}

代碼中用到了一個函數pow,

這個函數是用來表示次方的函數,所以需要引用標頭檔math.h。

當然,我們不採用pow函數也一樣可以完成編程。

在迴圈體外,我們可以定義一個輔助變數flag,令flag=1。

迴圈體中,我們只需要在結束末尾令flag=-flag,

這樣就可以使flag在1和-1之間不斷轉變,從而完成編程。

代碼如下:

#include<stdio.h>int main(){    int i, flag = 1;    float sum = 0.0;    for (i = 1; i <= 100; i++)    {        sum = sum + flag*(1.0 / i);        flag = -flag;    }    printf("sum is %f\n", sum);    system("pause");    return 0;}

最後附上程式啟動並執行結果:

用C語言實現:計算1/1-1/2+1/3-1/4+1/5 …… + 1/99 - 1/100 的值。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.