2、Kotlin基础(数组和循环练习题)

这一期是关于数组和循环的练习题:

第一题是这样的:

val array = // initalize array here(在这里填空)

val sizes = arrayOf("byte","kilobyte","megabyte","gigabyte","terabyte","petabyte","exabyte")

for((i, value) in array.withIndex())

{

println("1${sizes[i]}=${value.toLong()}bytes")

}

要求输出是这样的:

1 byte =1 bytes

1 kilobyte =1000 bytes

1 megabyte =1000000 bytes

1 gigabyte =1000000000 bytes

1 terabyte =1000000000000 bytes

1 petabyte =1000000000000000 bytes

1 exabyte =1000000000000000000 bytes

正确答案是:

val array = Array(7){1000.0.pow(it)}

注意:这里使用的是1000.0而不是1000

下一题是关于immutable的多选题,其中immutable意味着不能改变can not change:

题目不好复制 。所以截了图(包含正确答案):

多选

最后是一道编程题:

Basic example

Create an integer array of numbers callednumbers, from 11 to 15.

Create an empty mutable list for Strings.

Write aforloop that loops over the array and adds the string representation of each number to the list.

Challenge example

How can you use aforloop to create (a list of) the numbers between 1 and 100 that are divisible by 7?

答案是(基础例题没有给答案,答案是我自己写的):

val numbers = intArrayOf(11,12,13,14,15)var list :MutableList = mutableListOf()

for(number in numbers){

    list.add(number.toString())

}

下面的挑战例题,官方答案有两个,分别是:

var list3 : MutableList = mutableListOf()

for(i in 0..100 step 7)  list3.add(i)

print(list3)

或者:

for(i in 0..100 step 7) println(i.toString()+" - ")


需要注意的是:mutable是可变列表,包含了添加删除等方法

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容