Kotlin -- 九九乘法表(真的是表格!)

还记得初中的时候刚学编程,老师讲到for循环,布置的作业是打印九九乘法表。那么多年一转眼就过去了,学习新语言就来打印一个有中国特色的九九乘法表吧。


上代码:

fun main(args : Array){
    multiplicationTable()
}

fun multiplication(a: Int, b: Int) = a * b  //Kotlin新特性!!!简洁明了!

fun multiplicationTable(){

    for(i in 0..9){
        if(i==0){
            //打印第一行
            for(i in 0..9){
                if(i==0)
                    print("*\t")
                else
                    print("$i\t")

            }
            println()
        } else {
            print("$i\t")  //打印第一列

            for(j in 1..i){  
                //打印内容
                print(multiplication(i,j).toString()+"\t")
            }

            println()  //换行
        }
    }
}

为了学习Kotlin的特性,特意将乘法独立出来写(虽然只有一行=。=)


输出结果:

*   1   2   3   4   5   6   7   8   9   
1   1   
2   2   4   
3   3   6   9   
4   4   8   12  16  
5   5   10  15  20  25  
6   6   12  18  24  30  36  
7   7   14  21  28  35  42  49  
8   8   16  24  32  40  48  56  64  
9   9   18  27  36  45  54  63  72  81  

你可能感兴趣的:(Kotlin -- 九九乘法表(真的是表格!))