递归与非递归打印乘法口诀表--Scala(指令式、函数式思维练习)
1 object Test extends App 2 { 3 def printMultiTable() 4 { 5 var i = 1 6 while (i < 10) 7 { 8 var j = 1 9 while (j <= i) 10 { 11 val prod = i * j 12 if (j != 1) print(" ") 13 val str = s"$j * $i = $prod" 14 val k = str.length 15 // while (k <= 10) 16 // { 17 // print(" ") 18 // k = k + 1 19 // } 20 if (k < 10) 21 { 22 print(" " * (10 - k)) 23 } 24 print(str) 25 j += 1 26 } 27 println() 28 i += 1 29 } 30 } 31 32 // printMultiTable()//打印测试
//返回第i行第j列的单个乘法式子
33 def multiExpression(i: Int, j: Int): String = 34 { 35 val res = i * j 36 s"$j * $i = $res "//注意j在前 37 }
38 //乘法表,至第i行第j列 39 def multiTable(i: Int, j: Int, str: String): String = 40 { 41 if (i <= 0 && j <= 0) 42 { 43 str 44 } 45 else if (j == 1) 46 {
if(i == 1)
multiExpression(1, 1) + str
else 47 multiTable(i - 1, i - 1, "\n" + multiExpression(i, 1) + str )//在后面追加打印出的单个乘法式子,注意换行 48 } 49 else 50 { 51 multiTable(i, j - 1, multiExpression(i, j) + str) 52 } 53 } 54 55 println(multiTable(4, 4, ""))//打印测试 56
//返回第i行,从该行的第1到第j个式子; 一行 = 前j-1个式子 + 第j个式子 57 def multiLine(i: Int, j: Int, str: String): String = 58 { 59 if (j == 0) 60 { 61 str 62 } 63 else 64 { 65 multiLine(i, j - 1, multiExpression(i, j) + str) 66 } 67 } 68 //利用子表“加上”当前行的思维,递归 69 def multiTable2(i: Int): String = 70 { 71 if (i == 1) 72 { 73 "1 * 1 = 1 " 74 } 75 else 76 { 77 multiTable2(i - 1) + "\n" + multiLine(i,i,"") 78 } 79 80 81 } 82 83 println(multiTable2(3)) 84 }