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

C++中setprecision不生效输出小数多一位,如何固定保留两位小数?

问题原因
  • 核心错误:main 函数调用完 HatSize(height, weight); 后,额外写了 cout << HatSize; 语句。这里的HatSize是函数名,会被隐式转换为布尔值true,对应输出数字1,相当于在帽码计算结果末尾拼接了一个1,才会出现预期9.94实际输出9.941的问题。
  • 补充说明:如果删除多余代码后仍有极个别精度偏差,是浮点数二进制存储的固有特性,fixed+setprecision(2)默认采用四舍五入规则,正常场景下不会影响两位小数的输出要求。
解决方法
  1. 直接删除main函数中cout << HatSize;这行无用代码即可解决绝大多数场景下的问题。
  2. 如果需要更严格的精度控制,可以先将计算结果放大100倍取整后再缩小,避免浮点数近似存储带来的偏差,示例逻辑如下(需要引入<cmath>头文件):
double result = (userWeight / userHeight) * 2.9;
result = round(result * 100) / 100;
cout << fixed << setprecision(2) << result;
修正后完整代码
#include <iostream>
#include <iomanip>
// 若使用round方法请解除下一行注释
// #include <cmath>
using namespace std;

void HatSize(double userHeight, double userWeight) {
    double res = (userWeight / userHeight) * 2.9;
    // 可选精度校正逻辑:res = round(res * 100) / 100;
    cout << fixed << setprecision(2) << res;
}

int main(){
    double height;
    double weight;
    double age;
    cout << "Give me your height in inches, weight in pounds, and age in years. I will give you your hat size, jacket size (inches at chest)\nand waist size in inches." << endl;
    cin >> height >> weight >> age;
    HatSize(height, weight);
    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 22:24:03