Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
996 views
in Technique[技术] by (71.8m points)

swift - Make Int round off to nearest value

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 displays 2.

How can I make Example round off to closest number without changing it to a Double

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 as

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 did not test which version is faster.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...