Chciałbym zaproponować mniej eleganckie, choć bardziej precyzyjne rozwiązanie; działa tylko dla liczb docelowych.
Ten przykład zaokrągla podaną liczbę sekund do następnego pełnego 60:
int roundSeconds(int inDuration) {
const int k_TargetValue = 60;
const int k_HalfTargetValue = k_TargetValue/2;
int l_Seconds = round(inDuration); // [MININT .. MAXINT]
int l_RemainingSeconds = l_Seconds % k_TargetValue; // [-0:59 .. +0:59]
if (ABS(l_RemainingSeconds) < k_HalfTargetValue) { // [-0:29 .. +0:29]
l_Seconds -= l_RemainingSeconds; // --> round down
} else if (l_RemainingSeconds < 0) { // [-0:59 .. -0:30]
l_Seconds -= (k_TargetValue - ABS(l_RemainingSeconds)); // --> round down
} else { // [+0:30 .. +0:59]
l_Seconds += (k_TargetValue - l_RemainingSeconds); // --> round up
}
return l_Seconds;
}
Albo „The w ten sam sposób, możesz zrobić to w C "... –
dzięki obiema sposobom działa dobrze – Mark
50 * podłoga ((liczba/50) +0,5) może być trochę lepiej. – djschwartz