【问题标题】:How do you round off decimal places in C++?你如何在 C++ 中舍入小数位?
【发布时间】:2012-08-24 05:19:33
【问题描述】:

我需要帮助将浮点值四舍五入到小数点后一位。

我知道setprecision(x)cout << precision(x)。如果我想对整个浮点数进行四舍五入,这两种方法都有效,但我只对将小数四舍五入到十分位感兴趣。

【问题讨论】:

标签: c++ floating-point precision


【解决方案1】:

还有另一种不需要强制转换为 int 的解决方案:

#include <cmath>

y = floor(x * 10d) / 10d

【讨论】:

    【解决方案2】:
    #include <cmath>
    
    int main() {
        float f1 = 3.14159f;
        float f2 = 3.49321f;
        std::cout << std::floor(f1 * 10 + 0.5) / 10 << std::endl; 
        std::cout << std::floor(f2 * 10 + 0.5) / 10 << std::endl;
        std::cout << std::round(f1 * 10) / 10 << std::endl; // C++11
        std::cout << std::round(f2 * 10) / 10 << std::endl; // C++11
    }
    

    【讨论】:

      【解决方案3】:

      你可以这样做:

      int main()
      {
      
          float a = 4212.12345f;
          float b = a * 10.0f;
          float c = ((int)b) / 10.0f;
      
          cout << c << endl;
          return 0;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-11-12
        • 2022-01-06
        • 1970-01-01
        • 1970-01-01
        • 2018-10-01
        • 1970-01-01
        相关资源
        最近更新 更多