2017-06-18 54 views
0

我試圖獲取用戶輸入號碼並找到所有數字的總和。但是,我遇到了大數字問題,因爲它們不會在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)") 
+0

您是否按照[本答案](https://stackoverflow.com/a/25614523/2773311)的建議考慮使用['NSDecimalNumber'](https://developer.apple.com/documentation/foundation/nsdecimalnumber) )在你鏈接的帖子?它可以處理'A * 10^B'形式的數字,其中'B'高達127. – Arc676

+0

將它作爲字符串讀取它怎麼樣? – vacawama

+1

@ Arc676 - 爲了相應地設置期望值,尾數可以是38位數字,所以如果你想要整數精度,建議B最大爲127,這有點誤導。它最多爲38位數,然後你開始失去準確性。 – Rob

回答

0

你可以使用一個字符串來執行你描述的操作。 Loop through each character並將其轉換爲整數並添加到總和中。小心處理錯誤。

+0

我一直試圖獲取用戶輸入作爲字符串,建議,但我不能將用戶輸入字符串(鍵入inout字符串)轉換爲整數或字符串 –

+0

您將需要將每個字符轉換爲int 。如何遍歷字符並轉換爲整數的示例如下:https://stackoverflow.com/a/30771177/5894196。即使它是'inout',你仍然可以使用'characters'屬性。 –