You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于无穷级数计算π近似值,求解达标项数及代码调试

修正π级数计算代码并实现精度达标项数统计

你的代码没法满足需求,核心问题有两个:

  • 循环只跑20次,这个级数收敛极慢,20项的近似值连3.14都到不了,更别说更高精度的阈值
  • 完全没做检测首次达到3.14、3.141、3.1415、3.14159这些精度的逻辑,自然没法输出对应项数

下面是修正后的代码,既保留了逐项输出近似值的表格,又能统计并打印首次达到各精度的项数:

#include <stdio.h>
#include <math.h>

int main(void) {
    double pi = 0.0;
    double term = 1.0;
    double divisor = 1.0;
    // 标志变量,记录各精度是否已找到首次达标项数
    int found_314 = 0, found_3141 = 0, found_31415 = 0, found_314159 = 0;
    int count_314, count_3141, count_31415, count_314159;

    // 打印表格表头
    printf("%10s%25s\n", "Number of terms", "Approximation of pi");

    // 循环直到所有精度都找到,设置1000000次上限防止死循环
    for (int i = 1; i <= 1000000; i++) {
        pi += term / divisor;
        double current_pi = pi * 4.0;
        // 打印当前项的近似值
        printf("%10d%25.10f\n", i, current_pi);

        // 检查各精度是否首次达标
        if (!found_314 && fabs(current_pi - 3.14) < 0.005) {
            count_314 = i;
            found_314 = 1;
        }
        if (!found_3141 && fabs(current_pi - 3.141) < 0.0005) {
            count_3141 = i;
            found_3141 = 1;
        }
        if (!found_31415 && fabs(current_pi - 3.1415) < 0.00005) {
            count_31415 = i;
            found_31415 = 1;
        }
        if (!found_314159 && fabs(current_pi - 3.14159) < 0.000005) {
            count_314159 = i;
            found_314159 = 1;
            // 所有精度都找到,提前退出循环
            break;
        }

        term *= -1.0;
        divisor += 2.0;
    }

    // 打印各精度首次达标的项数
    printf("\n首次达到各精度所需项数:\n");
    printf("3.14: %d 项\n", count_314);
    printf("3.141: %d 项\n", count_3141);
    printf("3.1415: %d 项\n", count_31415);
    printf("3.14159: %d 项\n", count_314159);

    return 0;
}

关键改动说明

  • 移除固定循环次数:改成循环到所有目标精度都被检测到,同时加了1000000次的上限,避免极端情况死循环
  • 添加精度检测逻辑:用标志变量跟踪每个精度是否已找到首次达标项,每次计算后检查当前近似值与目标值的误差是否小于半个精度单位(比如检测3.14时,误差小于0.005,确保近似值落在[3.135, 3.145)区间,首次达到时记录项数)
  • 提前终止循环:当最后一个精度3.14159达标后,直接跳出循环,不用继续计算
  • 补充结果输出:循环结束后专门打印各精度对应的首次达标项数

注意:这个级数收敛非常慢,达到3.14159需要几十万次迭代,运行时可能需要等一会儿才能出结果。

内容的提问来源于stack exchange,提问作者Taqi haider

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 11:50:31