Finish: 03-datatypes - 数据类型转换

This commit is contained in:
2026-03-14 18:40:01 +08:00
parent 14ef0fad75
commit 86c554908e
+8 -8
View File
@@ -13,10 +13,10 @@ func exercise1() {
var floatValue float64 = 3.14159
// 将intValue转换为float64类型,赋值给result1
result1 := ____
result1 := float64(intValue)
// 将floatValue转换为int类型,赋值给result2(注意:会丢失小数部分)
result2 := ____
result2 := int(floatValue)
fmt.Printf("int → float64: %d → %.2f\n", intValue, result1)
fmt.Printf("float64 → int: %.5f → %d\n", floatValue, result2)
@@ -27,7 +27,7 @@ func exercise2() {
// 将字符串"123"转换为整数类型,使用strconv.Atoi
ageStr := "123"
age, err := strconv.____
age, err := strconv.Atoi(ageStr)
fmt.Printf("字符串 '%s' 转换为整数: %d (错误: %v)\n", ageStr, age, err)
}
@@ -37,7 +37,7 @@ func exercise3() {
// 将整数456转换为字符串,使用strconv.Itoa
score := 456
scoreStr := strconv.____
scoreStr := strconv.Itoa(score)
fmt.Printf("整数 %d 转换为字符串: '%s'\n", score, scoreStr)
}
@@ -48,7 +48,7 @@ func exercise4() {
// 将字符串"98.76"转换为float64类型
// 使用strconv.ParseFloat,第二个参数是位数(64表示float64)
priceStr := "98.76"
price, err := strconv.____
price, err := strconv.ParseFloat(priceStr, 64)
fmt.Printf("字符串 '%s' 转换为float64: %.2f (错误: %v)\n", priceStr, price, err)
}
@@ -61,10 +61,10 @@ func exercise5() {
var runeVal rune = 'A'
// 将byteVal转换为对应的字符
char1 := ____(byteVal)
char1 := byte(byteVal)
// 将runeVal转换为字符串
char2 := ____(runeVal)
char2 := string(runeVal)
fmt.Printf("byte(65) → 字符: '%c'\n", char1)
fmt.Printf("rune('A') → 字符串: '%s'\n", char2)
@@ -77,7 +77,7 @@ func exercise6() {
var b float64 = 3.5
// 计算a和b的和,需要类型转换
sum := ____ + b
sum := float64(a) + b
fmt.Printf("%d + %.1f = %.1f\n", a, b, sum)
}