2010-07-18 6 views

Répondre

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

Vous n'avez pas besoin de Boost du tout, juste la bibliothèque C incluse dans la bibliothèque C++. Plus précisément, vous devez inclure l'en-tête de cmath:

ronde un certain nombre: Ceil(): http://www.cplusplus.com/reference/clibrary/cmath/ceil/

Arrondir un numéro: étage(): http://www.cplusplus.com/reference/clibrary/cmath/floor/

Vous pouvez écrire votre propre fonction tour, puis :

#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; 
} 
4

Vous pouvez utiliser lround disponible en C99.

#include <cmath> 
#include <iostream> 

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

(sorties 1, 2, 2).

Vérifiez la documentation de votre compilateur si et/ou comment vous devez activer le support C99.

3

Boost Rounding Functions

Par exemple:

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

sortie est:

0 
0 
1 
1 
0 
-1 
-1 
Questions connexes