簡體   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