实验一 初步掌握Scala程序设计

  1. 可否定义一个sum函数呢?返回指定区间的值的和?例如,区间[1,4]的和为1+2+3+4=10返回指定区间值的平方的和呢?立方呢?
package com.spark.core.wc

import scala.io.Source

object temp {
  def main(args: Array[String]): Unit = {
    val x,y = readInt();
    print(sum((i:Int)=>i,x,y));
    //若要平方则改为sum((i:Int)=>i*i,x,y),立方同理
  }
  def sum(f:(Int)=>Int,x:Int,y:Int):Int={
    var num = 0;
    for (i <- x to y){
      num += f(i);
    }
    num
  }
}

2、定义一个gcd函数,计算两个数的最大公因数。

package com.spark.core.wc

import scala.io.Source

object temp {
  def main(args: Array[String]): Unit = {
    val x,y = readInt();
    print(gcd(x,y));
  }
  
  //辗转相除法求最大公因数
  def gcd (a:Int,b:Int):Int={
    if(b == 0) return a
    gcd(b,a%b)
  }
}

3、scala实现杨辉三角。

package com.spark.core.wc

import scala.io.Source

object temp {
  
  def main(args: Array[String]): Unit = {
    //输入n,输出n阶杨辉三角
    val n = readInt();
    val a = Array.ofDim[Int](n+1,n+1);
    for(i <- 1 to n){
      a(i)(0) = 1
      a(i)(i) = 1
    }
    for(i <- 2 to n){
      for (j <- 1 to i){
        a(i)(j) = a(i-1)(j-1) + a(i-1)(j);
      }
    }
    for(i <- 1 to n){
      for(j <- 1 to i){
        print(a(i)(j) + " ")
      }
      println()
    }
  }
  • 2
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值