1 #include <stdio.h> 2 3 /* 4 编写一个函数,输入 n 为偶数时,调用函数求 1/2+1/4+...+1/n,当输入 n 为奇数时,调用函数1/1+1/3+...+1/n(利用指针函数). 5 */ 6 7 //1/2 + 1/4 +...+ 1/n; 8 float 9 even(int n) { 10 float sum = 0; 11 for(int i = 2; i <=n; i+=2) 12 sum += (float)1 / i; 13 return sum; 14 } 15 16 //1/1 + 1/3 +...+ 1/n; 17 float 18 odd(int n) { 19 float sum = 0; 20 for(int i = 1; i <= n; i+=2) 21 sum += (float)1/i; 22 return sum; 23 } 24 25 //函数指针为参数. 26 float 27 sum(float (*s)(int), int i) { 28 return (*s)(i); 29 } 30 31 // main函数调用 32 int main() { 33 int i; 34 printf("请输入一个正整数:"); 35 scanf("%d", &i); 36 float s; 37 if(i % 2 == 0) 38 s = sum(even, i); 39 else 40 s = sum(odd, i); 41 printf("sum=%f", s); 42 }
ref: C语言函数指针基础
时间: 2024-11-29 04:13:37