Kotlin中的数值类型

编程入门 行业动态 更新时间:2024-10-10 23:26:47

Kotlin中的<a href=https://www.elefans.com/category/jswz/34/1770286.html style=数值类型"/>

Kotlin中的数值类型


在Kotlin中,Byte、Short、Int、Long、Float和Double是基本数据类型,用于表示不同范围和精度的数值。

  1. Byte(字节):Byte类型是8位有符号整数类型,取值范围为-128到127。在Kotlin中,可以使用字面值或toByte()函数创建Byte类型变量。

示例代码:

val byteValue: Byte = 10
val anotherByte: Byte = 20.toByte()
  1. Short(短整型):Short类型是16位有符号整数类型,取值范围为-32768到32767。可以使用字面值或toShort()函数创建Short类型变量。

示例代码:

val shortValue: Short = 100
val anotherShort: Short = 200.toShort()
  1. Int(整型):Int类型是32位有符号整数类型,取值范围为-231到231-1。在Kotlin中,可以使用字面值或toInt()函数创建Int类型变量。

示例代码:

val intValue: Int = 1000
val anotherInt: Int = 2000.toInt()
  1. Long(长整型):Long类型是64位有符号整数类型,取值范围为-263到263-1。可以使用字面值或toLong()函数创建Long类型变量。

示例代码:

val longValue: Long = 100000L
val anotherLong: Long = 200000.toLong()
  1. Float(单精度浮点型):Float类型是32位浮点数类型,可以表示大约6-7位有效数字的浮点数。在Kotlin中,可以使用字面值或toFloat()函数创建Float类型变量。

示例代码:

val floatValue: Float = 3.14f
val anotherFloat: Float = 2.718f.toFloat()
  1. Double(双精度浮点型):Double类型是64位浮点数类型,可以表示大约15-16位有效数字的浮点数。可以使用字面值或toDouble()函数创建Double类型变量。

示例代码:

val doubleValue: Double = 3.14159
val anotherDouble: Double = 2.71828.toDouble()
  1. 全部代码。

示例代码:

fun main() {val byteValue: Byte = 10println(byteValue) // 打印:10val anotherByte: Byte = 20.toByte()println(anotherByte) // 打印:20val shortValue: Short = 100println(shortValue) // 打印:100val anotherShort: Short = 200.toShort()println(anotherShort) // 打印:200val intValue: Int = 1000println(intValue) // 打印:1000val anotherInt: Int = 2000.toInt()println(anotherInt) // 打印:2000val longValue: Long = 100000Lprintln(longValue) // 打印:100000val anotherLong: Long = 200000.toLong()println(anotherLong) // 打印:200000val floatValue: Float = 3.14fprintln(floatValue) // 打印:3.14val anotherFloat: Float = 2.718f.toFloat()println(anotherFloat) // 打印:2.718val doubleValue: Double = 3.14159println(doubleValue) // 打印:3.14159val anotherDouble: Double = 2.71828.toDouble()println(anotherDouble) // 打印:2.71828
}

以上是Kotlin中Byte、Short、Int、Long、Float和Double类型的详细描述和示例代码。请注意,在示例代码中,字面值后的字母"L"用于标记Long类型,字面值后的字母"f"用于标记Float类型。

更多推荐

Kotlin中的数值类型

本文发布于:2023-12-07 19:45:11,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1671673.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数值   类型   Kotlin

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!