2017-06-18 33 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'属性。 –