c-函數指標(求奇數偶數的和)

來源:互聯網
上載者:User

標籤:函數   指標   c   函數指標   奇數   偶數   

 1 #include <stdio.h> 2  3 /* 4 編寫一個函數,輸入 n 為偶數時,調用函數求 1/2+1/4+...+1/n,當輸入 n 為奇數時,調用函數1/1+1/3+...+1/n(利用指標函數). 5 */ 6  7 //1/2 + 1/4 +...+ 1/n; 8 float 9 even(int n) {10     float sum = 0;11     for(int i = 2; i <=n; i+=2)12         sum += (float)1 / i;13     return sum;14 }15 16 //1/1 + 1/3 +...+ 1/n;17 float18 odd(int n) {19     float sum = 0;20     for(int i = 1; i <= n; i+=2)21         sum += (float)1/i;22     return sum;23 }24 25 //函數指標為參數.26 float27 sum(float (*s)(int), int i) {28     return (*s)(i);29 }30  31 // main函數調用32 int main() {33     int i;34     printf("請輸入一個正整數:");35     scanf("%d", &i);36     float s;37     if(i % 2 == 0)38         s = sum(even, i);39     else40         s = sum(odd, i);41     printf("sum=%f", s);42 }

 ref: C語言函數指標基礎

c-函數指標(求奇數偶數的和)

聯繫我們

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