gpt4 book ai didi

c# - 返回数字的最接近的倍数

转载 作者:太空狗 更新时间:2023-10-29 19:48:32 26 4
gpt4 key购买 nike

我需要一个函数,通过它我能够将数字转换为给定倍数的最接近值。

例如,我希望将数字数组设置为 16 的最近倍数,因此 2 = 0、5 = 0、11 = 16、17 = 16、30 = 32 等

谢谢

最佳答案

为此您只需要一些除法和舍入:

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。例如:

var x = Math.Round(1.5); // x is 2.0, like you'd expect
x = Math.Round(0.5); // x is 0. WAT?!

关于c# - 返回数字的最接近的倍数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2705542/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com