简体   繁体   中英

Rounding with c

I'm trying to convert in hours and minutes starting from times (recorded in an array) in minutes from midnight. But I see that there is a rounding error. For example, the departure time 583 (minutes from midnight), calculating the time and minutes like this:

583/60 = 9.716666

I take the whole part (9) hours. Then I take the decimal part and do this:

0.716666 * 60 = 42.99996

The minutes would be 43 but unfortunately I can not extrapolate this value rounding it up.

Some idea?

#include <stdio.h>

#define SIZE (int)sizeof(departures) / sizeof(departures[0])

int main(void) {
    int hours, minutes, mmin, fh, fm;
    float res;

    int departures[] = {480, 583, 679, 767, 840, 945, 1140, 1305};
    int Arrivals[]   = {616, 712, 91, 900, 968, 1075, 1280, 1438};

    for(int i = 0; i < SIZE; i++) {
        res = (float)departures[i] / 60;
        fh  = departures[i] / 60;
        fm  = ((float)departures[i] / 60 - fh) * 60;

        printf("%d) %d:%d (%f)\n", i, fh, fm, res);     
    }   

    return 0;
}

You can use round function:

#include <stdio.h>
#include <math.h>
 int main()
{
       float i=5.4, j=5.6;
       printf("round of  %f is  %f\n", i, round(i));
       printf("round of  %f is  %f\n", j, round(j));
       return 0;
}

Output:

round of 5.400000 is 5.000000

round of 5.600000 is 6.000000

One doesn't need floating-point at all with the remainder % operation. This is more numerically stable.

#include <stdio.h>  /* size_t printf */

int main(void) {
    unsigned departures[] = {480, 583, 679, 767, 840, 945, 1140, 1305};
    const size_t departures_size = sizeof departures / sizeof *departures;
    size_t i;

    for(i = 0; i < departures_size; i++)
        printf("%lu) %u:%u\n", (unsigned long)i,
        departures[i] / 60, departures[i] % 60);

    return 0;
}

I've changed the int to unsigned int so that one knows to not have negatives. See this question for why. This gives,

...
1) 9:43

You do the following:

583/60 = 9.716666

I take the whole part (9) hours. Then I take the decimal part and do this:

0.716666 * 60 = 42.99996

Why don't you do it like this?

583/60 = 9.716666

You take the whole part (9) hours. Then you do this:

583 - (9 * 60) = 43

Like this, you don't need to round:-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM