Ç - 舍入整数除法(而不是截断) [英] C - Rounding integer division (instead of truncating)
本文介绍了Ç - 舍入整数除法(而不是截断)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我很好奇,想知道我可以圆一个数字,最近的第十整数。举例来说,如果我有:
int类型的= 59/4;
这将是14.75浮点计算;我怎么能存储的号码15在一?
解决方案
int类型的= 59.0f / 4.0F + 0.5F;
这只是分配给一个int的时候,因为它放弃了后面的所有作品'。
编辑:
这种解决方案将只在例的最简单的工作。一个更强大的解决方案是:
unsigned int类型round_div(unsigned int类型红利,无符号整型除数)
{
收益率(红利+(除数/ 2))/除数;
}
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;
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;
This only works when assigning to an int as it discards anything after the '.'
Edit: This solution will only work in the simplest of cases. A more robust solution would be:
unsigned int round_div(unsigned int dividend, unsigned int divisor)
{
return (dividend + (divisor / 2)) / divisor;
}
这篇关于Ç - 舍入整数除法(而不是截断)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文