函数参数

61 阅读1分钟

1.函数参数的使用 2.定义函数的时候,不写(),那么在调用函数的时候,也不能写()

object t39 {
 //1.函数参数的使用
 def hello (name:String,age:Int,gender:String="女"):Unit = {
   println(s"hello,我是${name},${age}岁,性别:${gender}")
 // 定义函数的时候,不写(),那么在调用函数的时候,也不能写()
   def test:Uint = {
   println("test.....")
   }
   
   def main (args:Array[String]):{
   test//正确
   test()//错误的
   }
 }
  def main (args:Array[String]):Unit = {
    hello("小花",18,"女")
    hello("小明",19,"女")
    hello("小花",18,"女")//1.不写性别,默认为女
//    hello() //2.不写所有参数,全部使用默认值

    hello(age=18)//3.设置年龄为18,其他的参数使用默认值
    hello(gender="男",name="小李")//4.设置名字为小李,性别为屉,年龄使用默认值
  }
}

1.允许参数的个数不同,类型相同 2.变参:参数类型后边,加一个*

object t40 {
  //允许参数的个数不同,类型相同
  //变参:参数类型后边,加一个*
  def getSum(args:Int*):Int = {
   var sum = 0
    for(i <- args){
      sum += i
    }
    sum
  }
  def main():Unit = {
    val restul1 = getSum(1)
    val restul2 = getSum(4,1,2,3,5)
    println(restul1,restul2)
  }
}

1.判断一个数是不是素数

object t41 {
 def testTriandle(a:Double,b:Double,c:Double):Boolean = {
a+b>c && a+c>b && b+c>a
 }
  //判断一个数是不是素数
 def isPrime(num:Int):Boolean={
  var isPrimeNum = true
  for(i <- 2 ≤ to ≤ num-1){
   if(num % i == 0){
    isPrimeNum = false
   }
  }
  //最后一行,表示函数的返回值
  isPrimeNum
 }
 def main (args:Array[String]):Unit = {
  val r = testTriandle(1.0,2.0,2.0)
  println(r)
  val r1 = isPrime(9)
  println(r1)//false
  val r1 = isPrime
  println(r1)
 }
}