C Exercise 76
100 Classic C Language Examples
**Problem:** Write a function: when the input n is even, call a function to compute 1/2+1/4+...+1/n; when the input n is odd, call a function to compute 1/1+1/3+...+1/n (using a pointer function).
**Analysis:** None.
Example
// Created by www.runoob.com on 15/11/9.
// Copyright (c) 2015 Runoob Tutorial. 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 produces the following output:
请输入一个数字:2
0.500000