繁体   English   中英

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

[英]Rounding floating point numbers in C++ to one decimal place

我在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;
}  

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 ) );
    }
}

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

环绕间隔出错(3)

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

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

answer = static_cast<float>(static_cast<int>(number * 10.)) / 10.;

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

cout << setprecision(1) << number << endl;

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

rounded = truncf(original * 10) / 10;

但是,我同意Ben的意见,你绝对不应该检查确切的不平等。 如果需要比较,请使用epsilon

作为旁注,您似乎正在构建自己的(侵入式)链接列表。 C ++已经为您提供了各种容器,例如vectorlist 此外,您不必编写确定序列中最大值的函数,只需使用标准库中的适当算法即可。

#include <vector>
#include <algorithm>

std::vector<float> angles = {0.0, 355.5, 9.9};
float maximum = *std::maximum_element(angles.begin(), angles.end());

使用此功能,看起来很复杂,但问的是:

float float_one_point_round(float value)
{
        return ((float)((int)(value * 10))) / 10;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM