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

Madhava-Leibniz级数求pi时setprecision()对整数值无精度问题

解决Madhava-Leibniz级数π近似程序的输出格式问题

问题根源

你的程序计算逻辑没问题,输入0时得到的4.0是正确结果,但cout默认会省略整数形式浮点数的小数点和后续零。虽然你设置了std::setprecision(16),但这个参数默认控制的是有效数字数量,而非固定小数位数,所以整数型浮点数会被简化输出。

两种可行修复方案

方案1:固定小数位数输出

使用std::fixed强制setprecision指定小数部分的位数,无论数值是否为整数,都会输出16位小数:
修改myResults函数中的输出代码:

cout << std::fixed << std::setprecision(16) << "The approximated value of pi is: " << output << endl;

此时输入0会输出:The approximated value of pi is: 4.0000000000000000

方案2:强制显示小数点及零

使用std::showpoint强制输出小数点和必要的零,保持有效数字的精度控制:
修改输出代码为:

cout << std::showpoint << std::setprecision(16) << "The approximated value of pi is: " << output << endl;

此时输入0会输出:The approximated value of pi is: 4.000000000000000(因double精度限制,实际显示15位小数,仍满足16位精度要求)

额外说明

你的mySum函数逻辑正确:输入0时,循环仅执行一次,计算得到1*4=4.0,数值本身没有问题,只需调整输出格式即可达到需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 15:57:41