小编mml*_*mla的帖子

Swift中的字数统计

在Swift中编写简单的字数统计函数有什么更优雅的方法?

//Returns a dictionary of words and frequency they occur in the string
func wordCount(s: String) -> Dictionary<String, Int> {
    var words = s.componentsSeparatedByString(" ")
    var wordDictionary = Dictionary<String, Int>()
    for word in words {
        if wordDictionary[word] == nil {
            wordDictionary[word] = 1
        } else {
            wordDictionary.updateValue(wordDictionary[word]! + 1, forKey: word)
        }
    }
    return wordDictionary
}

wordCount("foo foo foo bar")
// Returns => ["foo": 3, "bar": 1]
Run Code Online (Sandbox Code Playgroud)

algorithm swift

6
推荐指数
1
解决办法
5997
查看次数

什么是奇数整数后面的推理在除以2时四舍五入?

将奇数整数除以2而不是错误的计算时,看到错误不是更好吗?

Ruby中的示例(我猜它在其他语言中是相同的,因为整数和浮点数是常见的数据类型):

39 / 2 => 19

我得到的输出不是19.5,因为我们要求整数的值除以整数,而不是浮点数(39.0)除以整数.我的问题是,如果这些数据类型的限制阻止它计算正确的值,为什么输出最不正确的值?

  • 正确= 19.5
  • Correct-ish = 20(四舍五入)
  • 最少纠正= 19

ruby math integer

1
推荐指数
1
解决办法
2359
查看次数

标签 统计

algorithm ×1

integer ×1

math ×1

ruby ×1

swift ×1