编写一个函数,输入大于1的整数,输入n为偶数时,调用函数求1/2+1/4+...+1/n,当输入n为奇数时,调用函数 求1/1+1/3+...+1/n(要求利用函数指针编程) 输入格式:"%d" 偶数输出:"Even=%f" 奇数输出:"Odd=%f" 程序运行示例1如下: 10 Even=1.141667 程序运行示例2如下: 9 Odd=1.787302
#include "stdio.h"
float peven(int n)
{
float s;
int i;
s = 0;
for (i = 2; i <= n; i += 2)
s += 1 / (float)i;
return(s);
}
float podd(int n)
{
float s;
int i;
s = 0;
for (i = 1; i <= n; i += 2)
s += 1 / (float)i;
return(s);
}
float dcall(float (*fp)(), int n)
{
float s;
s = (*fp)(n);
return(s);
}
main()
{
float sum;
int n;
while (1)
{
scanf("%d", &n);
if (n > 1)
break;
}
if (n % 2 == 0)
{
printf("Even=");
sum = dcall(peven, n);
}
else
{
printf("Odd=");
sum = dcall(podd, n);
}
printf("%f", sum);
}