返回数字的最接近倍数 [英] Returning the nearest multiple value of a number
问题描述
我需要一个函数,通过该函数,我可以将数字转换为给定倍数的最接近值。
I need a function by which I will be able to convert a number to a nearest value of a given multiple.
例如,我想要一个数字数组设置为16的近东倍数,因此2 = 0、5 = 0、11 = 16、17 = 16、30 = 32等
Eg i want an array of number to be set to the neareast multiple of 16, so 2 = 0, 5 = 0, 11 = 16, 17 = 16, 30 = 32 etc
谢谢
推荐答案
此操作所需的除法和舍入操作应该是全部:
Some division and rounding should be all you need for this:
int value = 30;
int factor = 16;
int nearestMultiple =
(int)Math.Round(
(value / (double)factor),
MidpointRounding.AwayFromZero
) * factor;
请谨慎使用此技术。 Math.Round(double)
重载认为邪恶的突变体 MidpointRounding.ToEven
是最好的默认行为,即使我们在学校之前都学过了CLR所说的 MidpointRounding.AwayFromZero
。例如:
Be careful using this technique. The Math.Round(double)
overload believes the evil mutant MidpointRounding.ToEven
is the best default behavior, even though what we all learned before in school is what the CLR calls MidpointRounding.AwayFromZero
. For example:
var x = Math.Round(1.5); // x is 2.0, like you'd expect
x = Math.Round(0.5); // x is 0. WAT?!
这篇关于返回数字的最接近倍数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!