Online Compiler C

#include <stdio.h> #include <math.h> int main() { // 用于存储总和、当前项的值 double sum = 0.0, term; // 控制符号(正负交替)、分子、分母相关变量 int sign = 1, numerator = 1, denominatorFactor = 1; int i = 0; // 迭代计数,辅助计算各项参数 while (1) { // 计算当前项的分母:(2i + 1) * (3^i) int denominator = (2 * i + 1) * pow(3, i); // 计算当前项的值 term = sign * (double)numerator / denominator; // 若当前项绝对值小于 1e-5,满足精度要求,停止循环 if (fabs(term) < 1e-5) { break; } // 累加到总和 sum += term; // 更新下一项的参数:符号取反、分子加 2、迭代计数加 1 sign = -sign; numerator += 2; i++; } // 按 %.3f 格式输出结果,保留三位小数 printf("%.3f\n", sum); return 0; }
1) This code calculates an infinite series sum until a term's absolute value becomes smaller than 0.00001 (1e-5). Each term alternates in sign and has a specific pattern for numerator and denominator. The final sum is printed with 3 decimal places.

2) Hints:
- The denominator calculation combines a linear term (2i+1) with an exponential term (3^i) - notice how these components change with each iteration.
- The loop termination condition checks the term's magnitude, not the sum, so the loop continues until individual terms become sufficiently small.