《快学Scala》第2章 控制结构和函数 练习

1. 一个数字如果为正数,则它的signum为1;如果是负数,则signum为-1;如果是0,则signum为0.编写一个函数来计算这个值。

/**
 * Created by Ibuki Suika on 2014/5/26.
 */
object ScalaApp {
  def signum(n: Int) = {
    if (n > 0) 1
    else if (n < 0) -1
    else 0
  }

  def main(args: Array[String]) {
    println(signum(0))
    println(signum(-2))
    print(signum(100))
  }
}
2.一个空的块表达式{}的值是什么?类型是什么?

没有值
类型是Unit
3.指出在Scala中何种情况下赋值语句x = y = 1是合法的。(提示:给x找个合适的类型定义。)

当x为Unit类型时合法
4.针对下列Java循环编写一个scala版。

for (int i = 10; i >= 0; i--) System.out.println(i);

/**
 * Created by Ibuki Suika on 2014/5/26.
 */
object ScalaApp {
  def main(args: Array[String]) {
    for (i <- 10.to(0, -1)) {
      println(i)
    }
  }
}
5. 编写一个过程countdown(n:Int),打印从n到0的数字。

/**
 * Created by Ibuki Suika on 2014/5/26.
 */
object ScalaApp {
  def countdown(n: Int) {
    for (i <- n.to(0, -1)) {
      println(i)
    }
  }

  def main(args: Array[String]) {
    countdown(10)
  }
}
6. 编写一个for循环,计算字符串中所有字母的Unicode代码的乘积。

/**
 * Created by Ibuki Suika on 2014/5/26.
 */
object ScalaApp {
  def main(args: Array[String]) {
    val s = scala.io.StdIn.readLine()
    var prod: BigInt = 1
    for (c <- s) {
      prod *= c.toInt
    }
    println(prod)
  }
}
7, 同样是解决前一个练习的问题,但这次不使用循环。

/**
 * Created by Ibuki Suika on 2014/5/26.
 */
object ScalaApp {
  def main(args: Array[String]) {
    val s = scala.io.StdIn.readLine()
    val prod = s.map(_.toLong).product
    println(prod)
  }
}
8.编写一个函数product(s: string),计算前面练习中提过的乘积。

/**
 * Created by Ibuki Suika on 2014/5/26.
 */
object ScalaApp {
  def product(s: String) = {
    s.map(_.toLong).product
  }

  def main(args: Array[String]) {
    val s = scala.io.StdIn.readLine()
    println(product(s))
  }
}
9. 把前一个练习中的函数改成递归函数。

/**
 * Created by Ibuki Suika on 2014/5/26.
 */
object ScalaApp {
  def product(s: String): Long = {
    if (s.length == 1) {
      s(0).toLong
    } else {
      s(0).toLong * product(s.substring(1))
    }
  }

  def main(args: Array[String]) {
    val s = scala.io.StdIn.readLine()
    println(product(s))
  }
}

10. 编写函数计算x^n,其中n是整数,使用如下的递归定义:

x^n = y^2,如果n是正偶数的话,这里的y=x^(n/2)

x^n = x*x^(n-1),如果n是正奇数的话

x^0 = 1

x^n = 1 / x^-n,如果n是负数的话

不得使用return语句。


package scalaapplication1

object Main {
  def count(x: Double, n: Int): Double = {
    if (n == 0) 1
    else if (n > 0 && n % 2 == 0) count(x, n / 2) * count(x, n / 2)
    else if (n > 0 && n % 2 != 0) x * count(x, n - 1)
    else 1 / count(x, -n)
  } 

  def main(args: Array[String]): Unit = {
    println(count(2, 2))
    println(count(2, 0))
    println(count(2, 3))
    println(count(2, 1))
    println(count(2, -2))

  }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值