c - 用 c 舍入

标签 c rounding

我正在尝试从午夜开始的时间(记录在数组中)开始以小时和分钟为单位进行转换。但是我看到有一个舍入错误。比如出发时间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;
}

最佳答案

你可以使用圆形函数:

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

输出:

round of 5.400000 is 5.000000

round of 5.600000 is 6.000000

关于c - 用 c 舍入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58331060/

相关文章:

c++ - 无法理解是否在 #define 中

c# - 舍入到偶数 131.575 结果是奇数而不是偶数

R Shiny - 如何舍入数字、转换为百分比并下载 .csv 文件

c++ - C++11 中的 std::nearbyint 与 std::round

c - 为什么 realloc 在这种情况下不能正常工作?

c - 如何使用 WinAPI 识别光驱中的光盘类型?

c - PIE 文件在链接期间是否给出了虚拟内存地址?

c - 用一个 for/While 或 do while 循环制作一个螺旋

google-bigquery - 如何在 BigQuery 中将数值转换为货币?

javascript 数学,以 .05 为增量四舍五入到小数点后两位