我試圖獲取用戶輸入號碼並找到所有數字的總和。但是,我遇到了大數字問題,因爲它們不會在Int64下注冊。任何想法,我可以使用什麼結構來存儲的價值? (我試過UINT64並沒有與底片很好地工作,但是,我喜歡的東西比大UINT64,反正。我在從Is there a number type with bigger capacity than u_long/UInt64 in Swift?實施UInt128很難)大於Int64的整數
import Foundation
func getInteger() -> Int64 {
var value:Int64 = 0
while true {
//we aren't doing anything with input, so we make it a constant
let input = readLine()
//ensure its not nil
if let unwrappedInput = input {
if let unwrappedInt = Int64(unwrappedInput) {
value = unwrappedInt
break
}
}
else { print("You entered a nil. Try again:") }
}
return value
}
print("Please enter an integer")
// Gets user input
var input = getInteger()
var arr = [Int]()
var sum = 0
var negative = false
// If input is less than 0, makes it positive
if input < 0 {
input = (input * -1)
negative = true
}
if (input < 10) && (input >= 1) && (negative == true) {
var remain = (-1)*(input%10)
arr.append(Int(remain))
input = (input/10)
}
else {
var remain = (input%10)
arr.append(Int(remain))
input = (input/10)
}
}
// Adds numbers in array to find sum of digits
var i:Int = 0
var size:Int = (arr.count - 1)
while i<=size {
sum = sum + arr[i]
i = (i+1)
}
// Prints sum
print("\(sum)")
您是否按照[本答案](https://stackoverflow.com/a/25614523/2773311)的建議考慮使用['NSDecimalNumber'](https://developer.apple.com/documentation/foundation/nsdecimalnumber) )在你鏈接的帖子?它可以處理'A * 10^B'形式的數字,其中'B'高達127. – Arc676
將它作爲字符串讀取它怎麼樣? – vacawama
@ Arc676 - 爲了相應地設置期望值,尾數可以是38位數字,所以如果你想要整數精度,建議B最大爲127,這有點誤導。它最多爲38位數,然後你開始失去準確性。 – Rob