函数参数的使用
object class3 {
def hello(name:String="小明", age:Int=17, gender:String="女"):Unit = {
println(s"hello,我是${name},${age}岁,性别:${gender}")
}
def main(args: Array[String]): Unit = {
hello("小花", 18, "女")
hello("小明", 19, "男")
hello("小花",18)
hello()
}
}
//设置年龄为十八,其它参数使用默认值 //设置名字为小李,性别为男,年龄为默认值
object class3 {
def hello(name:String="小明", age:Int=17, gender:String="女"):Unit = {
println(s"hello,我是${name},${age}岁,性别:${gender}")
}
def main(args: Array[String]): Unit = {
hello("小花", 18, "女")
hello("小明", 19, "男")
hello("小花",18)
hello()
hello(age = 18)
hello(gender = "男",name = "小李")
}
}
object class3 {
def getSum(args:Int*):Int = {
// [1,2,3,4]
var sum = 0
for(i <- args){
sum += i
}
sum
}
def main(args: Array[String]): Unit = {
val result1 = getSum(1)
val result2 = getSum(4,1,2,3,5)
println(result1, result2)
}
}
object class3 {
// 判断给定的三边,能否构成一个三角形?
def testTriangle(a:Double, b:Double, c:Double):Boolean = {
// 完成代码,判断三边是否能构成三角形(任意两边之和大于第三边)
a + b > c && a + c > b && b + c > a
}
// 判断一个数是不是素数
def isPrime(num:Int):Boolean = {
if (num <= 1) false
else {
// 从 2 到 num 的平方根遍历,判断是否有因子
var isPrime = true
for (i <- 2 to Math.sqrt(num).toInt if isPrime) {
if (num % i == 0) isPrime = false
}
isPrime
}
}
def main(args: Array[String]): Unit = {
val r = testTriangle(1.0, 2.0, 3.0)
println(r) // false
}
}