【发布时间】:2017-06-18 02:44:38
【问题描述】:
我正在尝试获取用户输入的数字并找到所有数字的总和。但是,我遇到了较大数字的问题,因为它们不会在 Int64 下注册。关于我可以使用哪些结构来存储价值的任何想法? (我尝试了 UInt64,但它在底片上效果不佳,但是,无论如何,我更喜欢比 UInt64 更大的东西。我很难从 Is there a number type with bigger capacity than u_long/UInt64 in Swift? 实现 UInt128)
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)")
【问题讨论】:
-
您是否考虑过在您链接的帖子中按照this answer 的建议使用
NSDecimalNumber?它可以处理A*10^B形式的数字,其中B最多为127。 -
把它读成字符串怎么样?
-
@Arc676 - 只是为了相应地设置期望值,尾数可以是 38 位长,所以如果你想要整数精度,建议 B 最高为 127 有点误导。它最多 38 位,然后你开始失去准确性。