商品价格计算
题目描述
电商平台中,商品的库存数量是整数类型,而单价是浮点数类型。需要将库存数量转换为浮点数,计算总价值;同时将计算出的总价值(浮点数)转换为整数(金额分)进行结算。
- 定义整数变量
stock(库存数量)= 250,浮点数变量price(单价,元)= 99.99- 将
stock转换为 float64 类型,计算总价值totalPrice = float64(stock) * price- 将
totalPrice转换为 int 类型(代表金额分,需先乘以 100)- 输出原始数值、总价值(保留 2 位小数)、转换后的金额分(整数)
输出示例
商品总价值(元):24997.50
总价值(分,整数):2499750
实现代码
Go
package main
import (
"fmt"
"math"
)
func main() {
// 1. 定义基础变量
stock := 250 // 整数:库存数量
price := 99.99 // 浮点数:商品单价(元)
// 2. 整数转浮点数,计算总价值
totalPrice := float64(stock) * price
fmt.Printf("商品总价值(元):%.2f\n", totalPrice)
// 3. 浮点数转整数(先乘以100转换为分,再取整)
totalPriceCent := int(math.Round(totalPrice * 100)) // Round 避免精度丢失导致的误差
fmt.Printf("总价值(分,整数):%d\n", totalPriceCent)
}
用户 ID 处理
题目描述
用户在前端输入的 ID 是字符串类型(如表单输入),后端存储和计算时需要转换为整数;同时,将数据库中存储的整数 ID 转换为字符串,用于生成用户专属链接。
- 定义字符串变量
idStr= "10086",将其转换为 int 类型变量idInt- 定义整数变量
userId= 9527,将其转换为字符串类型变量userIdStr- 输出转换前后的数值及类型信息
输出示例
字符串ID "10086" 转换为整数:10086
整数ID 9527 转换为字符串:"9527"
实现代码
Go
package main
import (
"fmt"
"strconv"
)
func main() {
// 1. 字符串转整数
idStr := "10086"
idInt, _ := strconv.Atoi(idStr) // Atoi = ASCII to integer
fmt.Printf("字符串ID \"%s\" 转换为整数:%d\n", idStr, idInt)
// 2. 整数转字符串
userId := 9527
userIdStr := strconv.Itoa(userId) // Itoa = integer to ASCII
fmt.Printf("整数ID %d 转换为字符串:\"%s\"\n", userId, userIdStr)
}