問題描述
我正在嘗試制作一個(gè)增長率計(jì)算器(Double
),它將結(jié)果四舍五入到最接近的整數(shù)并從那里重新計(jì)算,如下所示:
I'm trying to make a calculator of growth rate (Double
) that will round the result to the nearest Integer and recalculate from there, as such:
let firstUsers = 10.0
let growth = 0.1
var users = firstUsers
var week = 0
while users < 14 {
println("week (week) has (users) users")
users += users * growth
week += 1
}
但到目前為止我一直做不到.
but I've been unable so far.
編輯我是這樣做的:
var firstUsers = 10.0
let growth = 0.1
var users:Int = Int(firstUsers)
var week = 0
while users <= 14 {
println("week (week) has (users) users")
firstUsers += firstUsers * growth
users = Int(firstUsers)
week += 1
}
雖然我不介意它總是四舍五入,但我不喜歡它,因?yàn)?firstUsers
必須成為變量并在整個(gè)程序中更改(以便進(jìn)行下一次計(jì)算),我不希望它發(fā)生.
Although I don't mind that it is always rounding down, I don't like it because firstUsers
had to become a variable and change throughout the program (in order to make the next calculation), which I don't want it to happen.
推薦答案
Foundation
庫中有一個(gè)round
可用(其實(shí)在Darwin
,但是 Foundation
導(dǎo)入 Darwin
并且大多數(shù)時(shí)候你會(huì)想要使用 Foundation
而不是使用 Darwin
直接).
There is a round
available in the Foundation
library (it's actually in Darwin
, but Foundation
imports Darwin
and most of the time you'll want to use Foundation
instead of using Darwin
directly).
import Foundation
users = round(users)
在操場上運(yùn)行您的代碼,然后調(diào)用:
Running your code in a playground and then calling:
print(round(users))
輸出:
15.0
round()
總是在小數(shù)位為 >= .5
時(shí)向上舍入,在 時(shí)總是向下舍入..5
(標(biāo)準(zhǔn)舍入).您可以使用 floor()
強(qiáng)制向下舍入,使用 ceil()
強(qiáng)制向上舍入.
round()
always rounds up when the decimal place is >= .5
and down when it's < .5
(standard rounding). You can use floor()
to force rounding down, and ceil()
to force rounding up.
如果需要四舍五入到特定的地方,那么你乘以pow(10.0, number of places)
,round
,再除以pow(10,名額)
:
If you need to round to a specific place, then you multiply by pow(10.0, number of places)
, round
, and then divide by pow(10, number of places)
:
四舍五入到小數(shù)點(diǎn)后兩位:
Round to 2 decimal places:
let numberOfPlaces = 2.0
let multiplier = pow(10.0, numberOfPlaces)
let num = 10.12345
let rounded = round(num * multiplier) / multiplier
print(rounded)
輸出:
10.12
注意:由于浮點(diǎn)數(shù)學(xué)的工作方式,rounded
可能并不總是完全準(zhǔn)確.最好將其更多地考慮為舍入的近似值.如果您這樣做是為了顯示,最好使用字符串格式化來格式化數(shù)字,而不是使用數(shù)學(xué)來舍入它.
Note: Due to the way floating point math works, rounded
may not always be perfectly accurate. It's best to think of it more of an approximation of rounding. If you're doing this for display purposes, it's better to use string formatting to format the number rather than using math to round it.
這篇關(guān)于如何快速將 Double 舍入到最近的 Int?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!