gpt4 book ai didi

c# - 如何编写对称版本的对齐值公式(在 C# 中)

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:08:08 29 4
gpt4 key购买 nike

我想编写一个组件,可以将一个值向上移动一个增量,或者移动到最近的增量。

假设增量为 0.0005,对于 Up() 方法,这里将是预期的输入和输出:

  • 1.0005 -> 1.0010(以增量方式移动)
  • 1.0006 -> 1.0010(不是增量,所以移动到增量)
  • 1.0007 -> 1.0010
  • 1.0008 -> 1.0010
  • 1.0009 -> 1.0010
  • 1.0010 -> 1.0015(以增量方式移动)
  • 1.0011 -> 1.0015
  • 1.0012 -> 1.0015
  • 等等

而 Down() 方法会以相反的方式做同样的事情。

我想出了这个公式:

return (value + increment) - (value % increment);

我预计 Down() 方法会类似,但我找不到它是什么。我能够让它工作的唯一方法是:

decimal mod = value % increment;

return mod != 0 ? value - mod : value - increment

当然如果反向操作相同,那么公式应该相同。

最佳答案

    public static decimal Increment(decimal dec, decimal inc) {
var mod = (dec % inc);
return dec - Math.Abs(mod) + (inc < 0 && mod != 0 ? Math.Abs(inc) : 0) + inc;
}

没有三元运算符:

    public static decimal Increment(decimal dec, decimal inc) {
var mod = (dec % inc);
var signInc = Math.Sign(inc);
return dec - Math.Abs(mod) +
((decimal)(Math.Pow(signInc, 2) - signInc) / 2) *
Math.Abs(Math.Sign(mod)) *
Math.Abs(inc)
+ inc;

}

  ((decimal)(Math.Pow(signInc, 2) - signInc) / 2) * 
Math.Abs(Math.Sign(mod)) *
Math.Abs(inc)

替换三元表达式。 Math.Pow(signInc, 2) - signInc) / 2如果 inc 则返回 1为负,否则为 0。 Math.Abs(Math.Sign(mod))如果 mod 则返回 0否则为 0 和 1;如果 inc < 0 && mod != 0,则使第一个乘法的结果为 1否则为 0。

关于c# - 如何编写对称版本的对齐值公式(在 C# 中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18910996/

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