我试图获取用户输入号码并找到所有数字的总和。但是,我遇到了大数字问题,因为它们不会在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