【问题标题】:Integers Larger than Int64大于 Int64 的整数
【发布时间】: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 位,然后你开始失去准确性。

标签: ios swift xcode uint64


【解决方案1】:

您可以使用字符串来执行您描述的操作。 Loop through each character 并将其转换为整数并添加到总和中。小心处理错误。

【讨论】:

  • 按照建议,我一直在尝试将用户输入作为字符串获取,但我无法将用户输入字符串(输入输出字符串)转换为整数或字符串
  • 您需要将每个字符转换为 int。如何遍历字符并转换为整数的示例如下:stackoverflow.com/a/30771177/5894196。即使是inout,您仍然可以使用characters 属性。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-04-30
  • 2019-10-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-17
  • 1970-01-01
相关资源
最近更新 更多