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

练习题

1、一个数字如果为正数,则它的signum为1;如果是负数,则signum为-1;如果为0,则signum为0;编写一个函数来计算这个值。
def signum(num: Int): Int = {
  if (num > 0) 1 else if (num < 0) -1
  else 0
}
2、一个空的快表达式{}的值是什么?类型是什么?

使用Scala REPL,表达式{ }的值是(),类型Unit
这里写图片描述

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

在Scala中,赋值语句的返回值是Unit类型,因此需要把x定义成Unit类型即可。


scala> var x = {}
x: Unit = ()

scala> var y = 8
y: Int = 8

scala> x = y = 1
x: Unit = ()
4、针对下列Java循环编写一个Scala版本: for(int i=10;i>=0;i–) System.out.println(i);
for( i <- 0 to 10  reverse ) println(i)

for (i <- Range(0, 10).reverse) println(i)
5、编写一个过程countdown(n:Int),打印从n到0的数字。
def countdown(n: Int): Unit = {
  for (i <- 0 to n reverse) print(i + "\t")
}

def countdown(n: Int): Unit = {
  (0 to n reverse)foreach print
}

//test
countdown(10)
6、 编写一个for循环,计算字符串中所有字母的Unicode代码的乘积。举例来说,”Hello”中所有字符串的乘积为9415087488L。
val s = "Hello"
var result: Long = 1
for (ch <- s) result = result * ch
result
7、 同样是解决前一个练习的问题,但这次不使用循环。(提示:在Scaladoc中查看StringOps)
var result:Long = 1
"Hello".foreach(result *= _)
result
8、编写一个函数product(s:String),计算前面练习中提到的乘积
def product(s: String): Long = {
  var result: Long = 1
  s.foreach(result *= _)
  result
}
// test
var result = product("Hello")
9、 把前一个练习中的函数改成递归函数
def product(s: String):Long={
  if (null==s || s.isEmpty)
    0
  else if(s.length > 1)
    s.head * product(s.tail)
  else
    s.head
}

//test
product("Hello")

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

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

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

3) x^0 = 1

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

不得使用return语句

def power(x: BigDecimal, n: Int): BigDecimal = {
  if (n == 0)
    1
  else if (n < 0)
    1 / power(x, -n)
  else if (n % 2 == 0)
    power(x, n / 2) * power(x, n / 2)
  else
    x * power(x, n - 1)
}

//test
power(2, 4)
power(2, 0)
power(2, -5)