Ch02 控制结构和函数

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

scala> def signum(x:Int):Int = if(x>0)1 else if(x==00 else -1
signum: (x: Int)Int
 
scala> signum(100)
res6: Int = 1
 
scala> signum(0)
res7: Int = 0
 
scala> signum(-2)
res8: Int = -1
 
2. 一个空的块表达式{}的值是什么?类型是什么?
回答:一个空的块表达式{}的值()。类型是Unit。
scala> def test = {}
test: Unit
 
scala> val t={}
t: Unit = ()
 
 
3. 指出在Scala中何种情况下赋值语句 x=y=1 是合法的。(提示:给x找个合适的类型定义。)
在x是Unit类型时,赋值语句x=y=1是合法的。但是这样的结果也许不是你的本意。
 
scala> var = 0
y: Int = 0
 
scala> var 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)
 
5. 编写一个过程countdown(n: Int),打印从n到0的数字。
scala> def countdown(n: Int){ for(i <- 0.to(n).reverse) println(i) } //注意{}块前没有=号
countdown: (n: Int)Unit
 
scala> countdown(10)
10
9
8
7
6
5
4
3
2
1
0
 
6. 编写一个for循环,计算字符串中所有字母的Unicode代码的乘积。举例来说,“Hello”中所有字符的乘积为9415087488L。
scala> var i: Long=1for(ch <- "Hello") i = i * ch.toInt //注意,使用Int会得到错误的结果,因为发生上溢出。
i: Long = 9415087488
 
scala> Int.MaxValue
res28: Int = 2147483647
 
7. 同样是解决前一个练习的问题,但这次不使用循环。(提示:在Scaladoc中查看StringOps)
scala> var product: BigInt = 1"Hello".foreach(product *= _.toInt)
product: BigInt = 9415087488
 
  1. def foreach(f:(A)Unit):Unit
  2. [use case]Applies a function f to all elements of this string.
 
8. 编写一个函数 product(s: String),计算前面练习中提到的乘积。
scala> def product(s: String): BigInt = {var i: BigInt=1; s.foreach(i *= _.toInt); i}
product: (s: String)BigInt
 
scala> product("Hello")
res38: BigInt = 9415087488
 
9. 把前一个练习中的函数改成递归函数。
def product(s: String): BigInt={
 
    if(s == null || s.length == 0return 0
 
    else if( s.length == 1) s(0).toInt
 
    else s.head.toInt * product(s.tail)
 
}
 
10. 编写函数计算xn,其中n是整数,使用如下的递归定义:
  • xn=y2, 如果n是正偶数的话,这里的y=xn/2
  • xn·xn-1,如果n是正奇数的话。
  • x0=1。
  • xn=1/x-n,如果n是负数的话。
不得使用return语句。
 
def pow(x:Double, n:Int):BigDecimal={
 
  if(n == 0)  1
 
  else if(n > 0 && n % 2 == 0)  pow(x, n/2) * pow(x, n/2)
 
  else if(n > 0 && n % 2 == 1)  x * pow(x, n-1)
 
  else (n < 0)  1/pow(x, -n)
 
}
 
pow(0.1, -2)
 
//res122: BigDecimal = 1E+2
 
原文地址:https://www.cnblogs.com/chenjo/p/4436582.html