c++固定位数输出

无论是printf还是fixed等方案都会四舍五入,需要取精确位数方法和正常四舍五入方案:

int main() {
    //c++20新特性
    double num = 3.1415926535;
    std::cout << std::format("{:.4f}", num) << std::endl; // 输出: 3.1416(四舍五入)
    //cout
    std::cout << std::fixed << std::setprecision(4) << num << std::endl;
    //printf
    printf("%.4f\n", num); // 输出: 3.1416(四舍五入)
    
  //取精确位数
    double truncated = std::floor(num * 10000) / 10000;
    printf("%.4f\n", truncated); // 输出: 3.1415(截断)
    return 0;
}

posted @ 2025-08-07 10:22  lyrrr  阅读(27)  评论(0)    收藏  举报