C 練習(xí)實(shí)例76
題目:編寫一個(gè)函數(shù),輸入n為偶數(shù)時(shí),調(diào)用函數(shù)求1/2+1/4+...+1/n,當(dāng)輸入n為奇數(shù)時(shí),調(diào)用函數(shù)1/1+1/3+...+1/n(利用指針函數(shù))。
程序分析:無。
程序源代碼:
// Created by www.o2fo.com on 15/11/9. // Copyright © 2015年 W3Cschool教程. All rights reserved. // #include<stdio.h> #include<stdlib.h> double evenumber(int n); double oddnumber(int n); int main() { int n; double r; double (*pfunc)(int); printf("請(qǐng)輸入一個(gè)數(shù)字:"); scanf("%d",&n); if(n%2==0) pfunc=evenumber; else pfunc=oddnumber; r=(*pfunc)(n); printf("%lf\n",r); system("pause"); return 0; } double evenumber(int n) { double s=0,a=0; int i; for(i=2;i<=n;i+=2) { a=(double)1/i; s+=a; } return s; } double oddnumber(int n) { double s=0,a=0; int i; for(i=1;i<=n;i+=2) { a=(double)1/i; s+=a; } return s; }
以上實(shí)例運(yùn)行輸出結(jié)果為:
請(qǐng)輸入一個(gè)數(shù)字:2 0.500000
更多建議: