私はユーザー入力番号を取得し、すべての桁の合計を探しています。しかし、Int64の下で登録しないので、大きな数字で問題が発生しています。値を格納するためにどのような構造体を使うことができるかについての考えはありますか?あなたがすることができます(私はUInt64型を試してみましたが、それはネガと非常によく動作しませんでした、しかし、私はとにかく。私はIs there a number type with bigger capacity than u_long/UInt64 in Swift?からUInt128を実装苦労を抱えている、UInt64型よりも大きな何かを好む)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までであることを示唆するのは少し間違いです。 – Rob