作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我想编写一个组件,可以将一个值向上移动一个增量,或者移动到最近的增量。
假设增量为 0.0005,对于 Up() 方法,这里将是预期的输入和输出:
而 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/
我是一名优秀的程序员,十分优秀!