Latest web development tutorials

C Exercise Example 76

100 cases of classic C language 100 cases of classic C language

Title: Write a function that input n is an even number, call the function evaluation 1/2 + 1/4 + ... + 1 / n, when the input n is odd, the function is called 1/1 + 1/3 + .. . + 1 / n (use the pointer function).

Program Analysis: None.

Source Code:

//  Created by www.w3big.com on 15/11/9.
//  Copyright © 2015年 本教程. 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("请输入一个数字:");
    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;
}

Run the above example output is:

请输入一个数字:2
0.500000

100 cases of classic C language 100 cases of classic C language