加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala – 值foreach不是Int的成员?

发布时间:2020-12-16 10:06:45 所属栏目:安全 来源:网络整理
导读:我正在学习 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,我需要打印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

丑,对吧?

解决方法

当你在理解中使用< - 时,你需要提供一个与第一个这样的< - 的输出兼容的类型.在这里,您从行i< - 0到20创建一个Seq [Int],然后从下一行创建一个Int.相反,您可以只分配中间结果,并在结尾处生成一个列表(然后您可以打印出来或以其他方式使用). 另外,你应该注意到,通过转换到你所做的Int,你可以确保使用整数除法计算倒数,除了第一个幂之外,所有的倒数都会得到零 – 在收益率中将铸造转换为Int,这样你就有了双倒数. 总体:

val result = for {
     i <- 0 to 20
     pow = scala.math.pow(2,i)
     rec = 1/pow
} yield (pow.toInt + "t" + rec)

然后,您可以使用以下内容打印出结果:

println(result.mkString("n"))

输出将是这样的:

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
2048    4.8828125E-4
4096    2.44140625E-4
8192    1.220703125E-4
16384   6.103515625E-5
32768   3.0517578125E-5
65536   1.52587890625E-5
131072  7.62939453125E-6
262144  3.814697265625E-6
524288  1.9073486328125E-6
1048576 9.5367431640625E-7

此外,您可以更改yield以生成元组列表,然后格式化您稍后选择(将格式与生成分离):

val result = { ... // as before
} yield (i,pow,rec) // Could prove handy to keep the index,and keep pow as a Double for now

def printResults(results: List[(Int,Double,Double)],formatter: (Int,Double) => String) = results forEach { case (n,rec) =>
  println(formatter(n,rec))
}

def egFormatter(n: Int,pow: Double,rec: Double) = s"For n = $n,t 2^n = ${pow.toInt},t reciprocal = $rec"

printResults(results,egFormatter)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读