舍入整数除法(而不是截断) [英] Rounding integer division (instead of truncating)

查看:122
本文介绍了舍入整数除法(而不是截断)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很想知道如何将数字舍入到最接近的第十整数。例如,如果我有:

I was curious to know how I can round a number to the nearest tenth whole number. For instance, if I had:

int a = 59 / 4;

以浮点计算的14.75;如何将数字存储为a中的15?

which would be 14.75 calculated in floating point; how can I store the number as 15 in "a"?

推荐答案

int a = 59.0f / 4.0f + 0.5f;

这仅适用于分配给int,因为它会丢弃'。'之后的任何内容。

This only works when assigning to an int as it discards anything after the '.'

修改:
此解决方案仅适用于最简单的情况。一个更强大的解决方案是:

This solution will only work in the simplest of cases. A more robust solution would be:

unsigned int round_closest(unsigned int dividend, unsigned int divisor)
{
    return (dividend + (divisor / 2)) / divisor;
}

这篇关于舍入整数除法(而不是截断)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆