Easy Tutorial
❮ C Scope Rules C Function Mbtowc ❯

C Exercise Example 76

C Language Classic 100 Examples

Title: Write a function that, when the input n is even, calls a function to calculate 1/2 + 1/4 + ... + 1/n, and when the input n is odd, calls a function to calculate 1/1 + 1/3 + ... + 1/n (using pointer functions).

Program Analysis: None.

Example

//  Created by www.tutorialpro.org on 15/11/9.
//  Copyright © 2015年 tutorialpro.org. 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 above example outputs the following result when run:

Please enter a number: 2
0.500000

C Language Classic 100 Examples

❮ C Scope Rules C Function Mbtowc ❯