C ++ Abrunden von Zahlen von Null entfernt
Frage
Hallo ich möchte runden Doppel Zahlen wie folgt aus (weg von Null) in C ++:
4.2 ----> 5
5.7 ----> 6
-7.8 ----> -8
-34.2 ----> -35
Was ist der effizienteste Weg, dies zu tun?
Lösung
inline double myround(double x)
{
return x < 0 ? floor(x) : ceil(x);
}
Wie bereits erwähnt in der Artikel Huppie zitiert , dies am besten als ein Ausdruck kommt Vorlage, die für alle Schwimmertypen
funktioniertSiehe http://en.cppreference.com/w/cpp/ Ziffern- / math / Boden und http: //en.cppreference. com / w / cav / numerisch / math / Boden
oder dank Pax, eine nicht-Funktion Version:
x = (x < 0) ? floor(x) : ceil(x);
Andere Tipps
Es gibt einen schönen Artikel über ein ähnliches Problem auf CPlusPlus.com . Die einfache Lösung für Ihr Problem so etwas wie dies sein sollte:
double customRound( double value ) const {
return value < 0 ? floor( value ) : ceil( value );
}
Eine bessere Lösung ist der in dem Artikel erwähnt, der eine Vorlage verwendet:
//--------------------------------------------------------------------------
// symmetric round up
// Bias: away from zero
template <typename FloatType>
FloatType ceil0( const FloatType& value )
{
FloatType result = std::ceil( std::fabs( value ) );
return (value < 0.0) ? -result : result;
}
Versuch
double rounded = _copysign(ceil(abs(x)), x);
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow