C++ 以0.5的精度舍入浮点值

C++ 以0.5的精度舍入浮点值,c++,floating-point,numbers,C++,Floating Point,Numbers,如何将浮点值舍入到小数点后的单个数字,例如给定的18.0-18.4我想显示18.0或给定的18.5-19.0显示19.0等? 谢谢大家我会使用floor()函数。因为round()可能无法在编译器上实现 #include "stdafx.h" #include <math.h> int _tmain(int argc, _TCHAR* argv[]) { double input = 18.0; for (int i = 0; i < 10; i++, inp

如何将浮点值舍入到小数点后的单个数字,例如给定的18.0-18.4我想显示18.0或给定的18.5-19.0显示19.0等? 谢谢大家

我会使用floor()函数。因为round()可能无法在编译器上实现

#include "stdafx.h"
#include <math.h>

int _tmain(int argc, _TCHAR* argv[])
{
    double input = 18.0;
    for (int i = 0; i < 10; i++, input += 0.1 )
    {
        double output = floor( input + 0.5 );
        printf( "Input:%f Output:%f\n", input, output );
    }
    getchar();

    return 0;
}
#包括“stdafx.h”
#包括
int _tmain(int argc,_TCHAR*argv[]
{
双输入=18.0;
对于(int i=0;i<10;i++,输入+=0.1)
{
双输出=地板(输入+0.5);
printf(“输入:%f输出:%f\n”,输入,输出);
}
getchar();
返回0;
}
输出是这样的

使用

使用
地板(x+0.5)
会出现以下情况:

  • 负数。当然,代码可以为此尝试
    ceil(x-0.5)

  • 如果总和
    x+0.5
    可能会产生一个新整数的四舍五入答案:FP数刚好小于0.5。
    x
    的ULP(最低有效位二进制数字)为0.5或1.0的某些值

  • 注意,代码需要确保添加的
    0.5
    不需要额外的精度

    下面是一个候选人
    round\u alt()
    应该
    round()
    不存在
    round_alt()
    没有这些问题

    double round_alt(double x) {
      double ipart;
      // break into integer and fraction parts
      double fpart = modf(x, &ipart);
      if (fpart != 0.0) {
        if (x >= 0.5) {
          ipart += floor(fpart + 0.5);
        } else if (x <= -0.5) {
          ipart += ceil(fpart - 0.5);
        }
      }
      return ipart;
    }
    
    double round\u alt(双x){
    双ipart;
    //分成整数和分数两部分
    双fpart=modf(x和ipart);
    如果(fpart!=0.0){
    如果(x>=0.5){
    ipart+=地板(fpart+0.5);
    
    如果X不需要处理负数字,除非是圆到零。我在过去30年中从未使用过C++或C++编译器,没有<代码>循环()/代码>。