簡體   English   中英

使用Boost在C ++中舍入到最接近的數字?

[英]Rounding to nearest number in C++ using Boost?

有沒有辦法在Boost庫中舍入到最接近的數字? 我的意思是任何數字,2個,5個,17個等等等等。

或者還有另一種方法嗎?

您可以使用C99中的lround

#include <cmath>
#include <iostream>

int main() {
  cout << lround(1.4) << "\n";
  cout << lround(1.5) << "\n";
  cout << lround(1.6) << "\n";
}

(輸出1,2,2)。

檢查編譯器文檔是否和/或如何啟用C99支持。

提升舍入功能

例如:

#include <boost/math/special_functions/round.hpp>
#include <iostream>
#include <ostream>
using namespace std;

int main()
{
    using boost::math::lround;
    cout << lround(0.0) << endl;
    cout << lround(0.4) << endl;
    cout << lround(0.5) << endl;
    cout << lround(0.6) << endl;
    cout << lround(-0.4) << endl;
    cout << lround(-0.5) << endl;
    cout << lround(-0.6) << endl;
}

輸出是:

0
0
1
1
0
-1
-1
int nearest = 5;
int result = (input+nearest/2)/nearest*nearest;

實際上你根本不需要Boost,只需要C ++庫中包含的C庫。 具體來說,您需要包含cmath標頭:

匯總一個數字:ceil(): http ://www.cplusplus.com/reference/clibrary/cmath/ceil/

向下舍入一個數字:floor(): http//www.cplusplus.com/reference/clibrary/cmath/floor/

您可以編寫自己的循環函數:

#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <string>
#include <utility>

double roundFloat(double x)
{
    double base = floor( x );

    if ( x > ( base + 0.5 ) )
            return ceil( x );
    else    return base;
}

int main()
{
    std::string strInput;
    double input;

    printf( "Type a number: " );
    std::getline( std::cin, strInput );
    input = std::atof( strInput.c_str() );

    printf( "\nRounded value is: %7.2f\n", roundFloat( input ) );

    return EXIT_SUCCESS;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM