将C++中的浮点数舍入到一个小数位

abb*_*bas 2 c++ floating-point

我在c ++中有一个浮点数,数字可以是不同的形式,例如355.5或9.9(这是测试代码的输入).

我有一个功能

float return_max(angle_set_t *angles)  
{  
    float val;  
    float max;  
    max= angles->key;  
    while( angles != NULL )  
    {  
        val= angles->key;  
        if(max<=val)  
        {  
            max=val;  
        }  
        angles = angles->right;  
    }       
    return max;
}  
Run Code Online (Sandbox Code Playgroud)

max可以是浮点值.我想将值舍入到一个小数位.

我需要一个通用的解决方案,因此适用于355.555555和9.999999

float first_aset()
{
    //do somethig
    result=return_max();
    return result;
}

void main()
{
    if( first_aset(S, 357.0, 20.0 ) != 9.9 ||
        first_aset(T, 357.0, 20.0 ) != 9.9 )
    {
         printf("Error in wrap-around interval (3)\n");
         printf(" first in interval [357, 20) in S is %f, should be 9.9\n",
         first_aset(S, 357.0, 20.0 ) );
         printf(" first in interval [357, 20) in T is %f, should be 9.9\n",
         first_aset(T, 357.0, 20.0 ) );
    }
}
Run Code Online (Sandbox Code Playgroud)

在这里是问题..结果是:

环绕间隔出错(3)

首先在区间[357,20]中S是9.900000,应该是9.9

第一个区间[357,20]中的T是9.900000,应该是9.9

Jos*_*shD 6

answer = static_cast<float>(static_cast<int>(number * 10.)) / 10.;
Run Code Online (Sandbox Code Playgroud)

如果您只是尝试以该精度显示值,请尝试setprecision:

cout << setprecision(1) << number << endl;
Run Code Online (Sandbox Code Playgroud)

在你的代码中,你将float与double进行比较.这只会严重结束(任何浮点比较都会如此).如果你比较它可能(很少)工作9.9f

  • @Jon Rodriguez:他想要截断,所以`answer = Floor(number * 10.) / 10.;` (3认同)