使用遞歸求出 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>運行效果
