def printMultiplicationTable(n: Int): Unit = {
    for (i <- 1 to n) {
      for (j <- 1 to i) {
        print(s'$j * $i = ${i * j}	')
      }
      println()
    }
  }

  val n = scala.io.StdIn.readInt()
  printMultiplicationTable(n)

该代码使用 Scala 语言编写了一个名为 printMultiplicationTable 的函数,该函数接受一个整数 n 作为参数,并打印出从 1 到 n 的乘法表。

代码解释:

  • def printMultiplicationTable(n: Int): Unit = { ... } 定义了一个名为 printMultiplicationTable 的函数,它接受一个整数 n 作为参数,返回值类型为 Unit,表示函数不返回值。
  • for (i <- 1 to n) { ... } 使用 for 循环遍历从 1 到 n 的整数,代表乘法表的行数。
  • for (j <- 1 to i) { ... } 使用嵌套的 for 循环遍历从 1 到 i 的整数,代表乘法表的列数。
  • print(s'$j * $i = ${i * j} ') 打印当前行和列的乘积,并使用 添加一个制表符,用于格式化输出。
  • println() 打印一个换行符,用于换行到下一行。
  • val n = scala.io.StdIn.readInt() 从终端读取用户输入的整数并赋值给变量 n
  • printMultiplicationTable(n) 调用 printMultiplicationTable 函数,传入用户输入的整数 n 作为参数。

使用方法:

  1. 将代码保存为 .scala 文件。
  2. 使用 Scala 编译器编译代码。
  3. 运行编译后的程序。
  4. 在终端输入一个整数(1-9),程序将打印出对应的乘法表。
Scala 函数实现 1-9 整数乘法表

原文地址: https://www.cveoy.top/t/topic/knsK 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录