过关练习

41 阅读2分钟

1.编写一个函数,他的入参是一个表示年份的整数,返回值是一个bool值,判断这个年份是否为闰年

object Base59 {
  def isLeapYear(year: Int): Boolean = {
    (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)
  }

  def main(args: Array[String]): Unit = {
    println(isLeapYear(2020))
    println(isLeapYear(2021))
  }
}

2.编写一个函数,用来求f(100)的值。其中f(n)=1-1/2+1/3-1/4+...1/n

object Base60 {
  def calculateF(n: Int): Double = {
    var result = 0.0
    for (i <- 1 to n) {
      if (i % 2 == 1) result += 1.0 / i
      else result -= 1.0 / i
    }
    result
  }

  def main(args: Array[String]): Unit = {
    println(calculateF(100))  // 输出 f(100) 的计算结果
  }
}

3.编写一个函数,用来求斐波那契数列数列的前20项。其中f(1)=f(2)=1,f(n)=f(n-1)+f(n-2)

object Base61 {
  def fibonacci(n: Int): Int = {
    if (n == 1 || n == 2) 1
    else fibonacci(n - 1) + fibonacci(n - 2)
  }

  def main(args: Array[String]): Unit = {
    for (i <- 1 to 20) {
      print(fibonacci(i) + " ")
    }
  }
}

4.编写一个函数,允许用户输入一个整数年份,如果用户输入的是闰年就停止输入,否则就一直提示用户输入

import scala.io.StdIn
object Base62 {
  def isLeapYear(year: Int): Boolean = {
    (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)
  }

  def inputUntilLeap(): Unit = {
    while (true) {
      println("请输入一个整数年份:")
      val year = StdIn.readInt()
      if (isLeapYear(year)) {
        println("输入的是闰年,程序停止。")
        return
      } else {
        println("输入的不是闰年,请继续输入。")
      }
    }
  }

  def main(args: Array[String]): Unit = {
    inputUntilLeap()
  }
}

5.对成绩(100,51,55,67,59,89)进行处理,分数在56-59之间,就设置60分,得到的新成绩为(100,51,55,67,60,89)

object Base63 {
  def processScores(scores: List[Int]): List[Int] = {
    scores.map(score => if (score >= 56 && score <= 59) 60 else score)
  }

  def main(args: Array[String]): Unit = {
    val scores = List(100, 51, 55, 57, 69, 58, 90)
    println(processScores(scores))
  }
}