object Test extends App
{
def printMultiTable()
{
var i = 1
while (i < 10)
{
var j = 1
while (j <= i)
{
val prod = i * j
if (j != 1) print(" ")
val str = s"$j * $i = $prod"
val k = str.length
// while (k <= 10)
// {
// print(" ")
// k = k + 1
// }
if (k < 10)
{
print(" " * (10 - k))
}
print(str)
j += 1
}
println()
i += 1
}
}
// printMultiTable()//打印测试
//返回第i行第j列的单个乘法式子
def multiExpression(i: Int, j: Int): String =
{
val res = i * j
s"$j * $i = $res "//注意j在前
}
//乘法表,至第i行第j列
def multiTable(i: Int, j: Int, str: String): String =
{
if (i <= 0 && j <= 0)
{
str
}
else if (j == 1)
{
if(i == 1)
multiExpression(1, 1) + str
else
multiTable(i - 1, i - 1, "\n" + multiExpression(i, 1) + str )//在后面追加打印出的单个乘法式子,注意换行
}
else
{
multiTable(i, j - 1, multiExpression(i, j) + str)
}
}
println(multiTable(4, 4, ""))//打印测试
//返回第i行,从该行的第1到第j个式子; 一行 = 前j-1个式子 + 第j个式子
def multiLine(i: Int, j: Int, str: String): String =
{
if (j == 0)
{
str
}
else
{
multiLine(i, j - 1, multiExpression(i, j) + str)
}
}
//利用子表“加上”当前行的思维,递归
def multiTable2(i: Int): String =
{
if (i == 1)
{
"1 * 1 = 1 "
}
else
{
multiTable2(i - 1) + "\n" + multiLine(i,i,"")
}
}
println(multiTable2(3))
}