1#include <stdio.h>2 3 /*4 Write a function, when the input n is even, call the function to 1/2+1/4+...+1/n, when the input n is odd, call the function 1/1+1/3+...+1/n (using pointer function).5 */6 7 //+...+ + 1/n;8 float9Even (intN) {Ten floatsum =0; One for(inti =2; I <=n; i+=2) ASum + = (float)1/i; - returnsum; - } the - //1/1 + 1/3 +...+ 1/n; - float -OddintN) { + floatsum =0; - for(inti =1; I <= N; i+=2) +Sum + = (float)1/i; A returnsum; at } - - //The function pointer is a parameter. - float -Sumfloat(*s) (int),inti) { - return(*s) (i); in } - to //Main function Call + intMain () { - inti; theprintf"Please enter a positive integer:"); *scanf"%d", &i); $ floats;Panax Notoginseng ifI2==0) -s =sum (even, i); the Else +s =sum (odd, i); Aprintf"sum=%f", s); the}
Ref:c language function Pointer basics
C-Function pointers (for odd and even numbers)