float

Admin Persönliche Seite #5421
Lesenswert?
• ▲
▼
Grundsätzlich kannst du das so umwandeln:
i = (int) f;

Um das Ganze aber noch ordentlich zu runden wird es komplizierter. 
Flgendes hab ich mal irgendwo gefunden:


--- test program for Jam's round() ---

#include <limits.h>
#include <math.h>
#include <assert.h>

const int int_min = int(INT_MIN);
const int int_max = int(INT_MAX);

int round(double f) {
   assert( f>=int_min && f<=int_max );
   if ( f >= 0.0 ) return int(f+0.5);
   else return int(ceil(f-0.5)); // unlike -int((-f)+0.5), works with 
INT_MIN
}

main() {
    assert( round(0) == 0 );
    assert( round(0.2) == 0 );
    assert( round(0.5) == 1 );
    assert( round(1.7) == 2 );
    assert( round(-1.7) == -2 );
    assert( round(-1.2) == -1 );
    assert( round(int_min/2) == int_min/2 );
    assert( round(int_min+1) == int_min+1 );
    assert( round(int_max-1) == int_max-1 );
    assert( round(int_min) == int_min );
    assert( round(int_max) == int_max );
}

Antwort schreiben

Bitte melde dich an, um einen Beitrag zu schreiben.

oder

Mit Google-Account einloggen

Die Registrierung ist kostenlos und dauert nur eine Minute.

Jetzt registrieren