简体   繁体   English

用 c 四舍五入

[英]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(从午夜开始的分钟数),计算时间和分钟数如下:

583/60 = 9.716666 583/60 = 9.716666

I take the whole part (9) hours.我把整个部分(9)小时。 Then I take the decimal part and do this:然后我取小数部分并这样做:

0.716666 * 60 = 42.99996 0.716666 * 60 = 42.99996

The minutes would be 43 but unfortunately I can not extrapolate this value rounding it up.分钟数为 43,但不幸的是,我无法将这个值四舍五入。

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:您可以使用圆形 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: Output:

round of 5.400000 is 5.000000 5.400000 轮是 5.000000

round of 5.600000 is 6.000000 5.600000 轮是 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.我已将int更改为unsigned int以便人们知道没有底片。 See this question for why. 请参阅此问题以了解原因。 This gives,这给出了,

...
1) 9:43

You do the following:您执行以下操作:

583/60 = 9.716666 583/60 = 9.716666

I take the whole part (9) hours.我把整个部分(9)小时。 Then I take the decimal part and do this:然后我取小数部分并这样做:

0.716666 * 60 = 42.99996 0.716666 * 60 = 42.99996

Why don't you do it like this?你为什么不这样做呢?

583/60 = 9.716666 583/60 = 9.716666

You take the whole part (9) hours.你花了整个部分(9)小时。 Then you do this:然后你这样做:

583 - (9 * 60) = 43 583 - (9 * 60) = 43

Like this, you don't need to round:-)像这样,你不需要四舍五入:-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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