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
 

最新文章

  1. UP Board 超详细开箱评测
  2. linux系统文件权限
  3. Makefile总述②文件命名、包含其他文件makefile、变量、重建重载、解析
  4. CSS table-layout 、border-collapse属性
  5. mysql中批量替换数据库中的内容的sql
  6. Unity3D Keynote
  7. 【HNOI2004】敲砖块(动态规划)
  8. 关于&lt;input type=&quot;date&quot;&gt;这种取值的问题 【原创】
  9. select简单循环嵌套
  10. Rgb2Gray
  11. R 包
  12. 【linux】之Centos6.x升级glibc
  13. uiautomator 代码记录 : 随机发送短信
  14. C#退出模式
  15. firedac引擎DATASNAP多表查询和多表提交
  16. github上fork别人的代码之后,如何保持和原作者同步的更新
  17. 安装nvidia driver
  18. jfinal框架教程
  19. [Flex] 组件Tree系列 —— 运用variableRowHeight和wordWrap设置可变行高
  20. .net的根目录区别

热门文章

  1. Delphi调用java so
  2. C语言 &#183; 出栈次序
  3. 消息中间件系列五:RabbitMQ的使用场景(异步处理、应用解耦)
  4. Java 判断字符串 中文是否为乱码
  5. PXE(preboot execution environment):【网络】预启动执行环节:安装 debian 9系列:成功
  6. ajax方法如何给全局变量赋值
  7. webapi 统一处理时间格式
  8. macOS 10.13 High Sierra odoo11 开发配置--完整版
  9. threding模块的其他用法
  10. 进程锁Lock