使Int缩小到最接近的值 [英] Make Int round off to nearest value
问题描述
我有两个Int值(它们必须是Ints),并且我想让它们在等式中舍入到最接近的值;
var Example = Int()
/ pre>
var secondExample = Int()
示例=(secondExample / 7000)
此方程使变量
实例
始终舍入到最低值。例如,数字如下:var Example = Int()
var secondExample:Int = 20000
示例=(20000/7000)
20000/7000等于2.857。 ..但变量
示例
显示2
。
如何使
示例
四舍五入到最接近的数字而不将其更改为Double解决方案对于非负的整数,以下函数给出
纯整数运算中所需的结果:
func divideAndRound(分子:Int,_分母:Int) - >Int {
return(2 *分子+分母)/(2 *分母)
}
示例:
print(20000.0 / 7000.0)// 2.85714285714286
print(divideAndRound(20000, ))// 3(四舍五入)
print(10000.0 / 7000.0)// 1.42857142857143
print(divideAndRound(10000,7000))// 1(舍入)
想法是
a 1 2 * a + b
- + - = ---------
b 2 2 * b
这里是一个可能的实现,用于任意签名的
整数也不会溢出:func divideAndRound(num:Int,_ den:Int) - > Int {
return num / den +(num%den)/(den / 2 + den%2)
}
(基于@ user3441734的更新解决方案,所以我们现在有一个参考
循环:)
也是
ldiv
函数,它计算商b $ b和分数的剩余部分,所以最后一个函数也可以是
实现为func divideAndRound(num:Int,_ den:Int) - > int {
let div = ldiv(num,den)
let div2 = ldiv(den,2)
return div.quot + div.rem /(div2.quot + div2.rem)
}
(我没有测试哪个版本更快)。
I've got two Int values (they have to be Ints) and I want them to round off to the nearest value when in an equation;
var Example = Int() var secondExample = Int() Example = (secondExample / 7000)
This equation makes the variable
Example
always round down to the lowest value. Say for example that the numbers are the following;var Example = Int() var secondExample : Int = 20000 Example = (20000 / 7000)
20000 / 7000 equals 2.857... But the variable
Example
displays2
.How can I make
Example
round off to closest number without changing it to a Double解决方案For nonnegative integers, the following function gives the desired result in pure integer arithmetic :
func divideAndRound(numerator: Int, _ denominator: Int) -> Int { return (2 * numerator + denominator)/(2 * denominator) }
Examples:
print(20000.0/7000.0) // 2.85714285714286 print(divideAndRound(20000, 7000)) // 3 (rounded up) print(10000.0/7000.0) // 1.42857142857143 print(divideAndRound(10000, 7000)) // 1 (rounded down)
The idea is that
a 1 2 * a + b - + - = --------- b 2 2 * b
And here is a possible implementation for arbitrarily signed integers which also does not overflow:
func divideAndRound(num: Int, _ den: Int) -> Int { return num / den + (num % den) / (den / 2 + den % 2) }
(Based on @user3441734's updated solution, so we have a reference cycle between our answers now :)
There is also a
ldiv
function which computes both quotient and remainder of a division, so the last function could also be implemented asfunc divideAndRound(num: Int, _ den: Int) -> Int { let div = ldiv(num, den) let div2 = ldiv(den, 2) return div.quot + div.rem / (div2.quot + div2.rem) }
(I did not test which version is faster.)
这篇关于使Int缩小到最接近的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!