首页 > 解决方案 > 用 c 舍入

问题描述

我正在尝试从午夜开始的时间(记录在数组中)以小时和分钟为单位进行转换。但我看到有一个舍入错误。例如出发时间 583(从午夜开始的分钟数),计算时间和分钟数如下:

583/60 = 9.716666

我把整个部分(9)小时。然后我取小数部分并这样做:

0.716666 * 60 = 42.99996

分钟数为 43,但不幸的是,我无法将这个值四舍五入。

有什么想法?

#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;
}

标签: crounding

解决方案


您可以使用圆形功能:

#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;
}

输出:

5.400000 轮是 5.000000

5.600000 轮是 6.000000


推荐阅读