c - 用 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;
}
解决方案
您可以使用圆形功能:
#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
推荐阅读
- android - 如何在android中的其他布局之上显示布局
- python - 我想让python在这个计算器中识别“num1”和“num2”是否是数字,以便python可以通知你没有输入有效的东西
- git - 解决报告的合并冲突后,是否需要重复运行相同的合并命令?
- javascript - 使用 lambda 在 socket.io 中发送 2 个参数的正确方法是什么?(在客户端和服务器中打印时我得到未定义)
- javascript - React - 子到父回调不起作用
- postgresql - 将json数组元素插入表的函数
- apache-spark - Spark Select 对不同对象的 JSON 数组进行选择
- arrays - 如何修复 yii2 BaseActiveRecord 无法显示、私有的 mongodb 数组?
- r - 对于 XY 坐标对,使用数据表,计算行数,将完整集写入 DT1,DT2 部分集
- raku - `MAIN()` 参数中的字符串匹配