【发布时间】:2015-09-24 14:29:40
【问题描述】:
我正在学习 scala,我需要打印 2 的幂及其从 0 到 20 的倒数
我正在做的是
scala> for {
| i <- 0 to 20
| pow <- scala.math.pow(2, i).toInt
| rec <- 1/pow
| } println(pow + "\t" + rec)
但我认为错误为
<console>:13: error: value foreach is not a member of Int
pow <- scala.math.pow(2, i).toInt
^
我知道pow 是不可迭代的,但是我之前如何计算它以便我重复使用它?
否则,我将其重新计算为
scala> for(i <- 0 to 10) println(scala.math.pow(2, i).toInt + "\t" + 1/scala.math.pow(2,i))
1 1.0
2 0.5
4 0.25
8 0.125
16 0.0625
32 0.03125
64 0.015625
128 0.0078125
256 0.00390625
512 0.001953125
1024 9.765625E-4
丑,对吧?
【问题讨论】:
标签: scala