C Exercise Example 76

100 Classic C Examples

Title:Write a function. When the input n is even, call the function to compute 1/2+1/4+...+1/n; when the input n is odd, call the function 1/1+1/3+...+1/n (using pointer functions).

Program analysis:None.

Example

// Created by www.example.com on 15/11/9. // Copyright © 2015 Example. 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("Please enter a number:"); 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; }

The output result of running the above example is:

请输入一个数字:2
0.500000

100 Classic C Examples

other extensions