使用递归求出 1 + 1/3 -1/5 + 1/7 - 1/9 +... + 1/n的值。
1>程序代码
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <pthread.h>
#include <semaphore.h>
#include <wait.h>
#include <signal.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <semaphore.h>
#include <sys/msg.h>
#include <sys/shm.h>
#include <sys/un.h>
typedef struct sockaddr_in addr_in_t;
typedef struct sockaddr addr_t;
typedef struct sockaddr_un addr_un_t;
// 定义递归函数
double calculate(int n)
{
// 递归终止条件
if (n == 1)
{
return 1.0; // 当 n 为 1 时,直接返回 1.0
}
else if (n == 3)
{
return 1.0 + 1.0 / 3; // 当 n 为 3 时,返回 1 + 1/3
}
else
{
// 递归调用,计算从 1 到 n-2 的序列值
double previousResult = calculate(n - 2);
// 判断当前项的符号
double currentTerm = 1.0 / n; // 当前项的绝对值
if ((n - 1) % 4 == 0)
{
currentTerm = -currentTerm; // 如果 n-1 是 4 的倍数,符号为负
}
// 将当前项加到之前的结果中
return previousResult + currentTerm;
}
}
int main(int argc, const char *argv[])
{
int n;
printf("请输入一个正奇数n: ");
scanf("%d", &n);
// 检查输入是否为正奇数
if (n <= 0 || n % 2 == 0)
{
printf("输入无效,请输入一个正奇数。\n");
} else
{
double result = calculate(n);
printf("计算结果为: %.10f\n", result);
}
return 0;
}
2>运行效果