Golang如何将整数和浮点相乘
我试图调整图像的尺寸,但在编译时遇到一个常量0.8截断为整数的错误。这是我的密码Golang如何将整数和浮点相乘,go,Go,我试图调整图像的尺寸,但在编译时遇到一个常量0.8截断为整数的错误。这是我的密码 b := img.Bounds() heightImg := b.Max.Y // height of image in pixels widthImg := b.Max.X // width of image in pixels const a = .80 height := int(heightImg * a) // reduce height by 20% width := int(widthImg
b := img.Bounds()
heightImg := b.Max.Y // height of image in pixels
widthImg := b.Max.X // width of image in pixels
const a = .80
height := int(heightImg * a) // reduce height by 20%
width := int(widthImg * a) // reduce width by 20%
// resize image below which take in type int, int in the 2nd & 3rd parameter
new_img := imaging.Resize(img,width,height, imaging.Lanczos)
我是刚来golang的新手,但这里的代码给了我一个错误
height := int(heightImg * a)
width := int(widthImg * a)
任何建议都很好如果您想将浮点数相乘,需要将数字转换为浮点数:
height := int(float64(heightImg) * a)
width := int(float64(widthImg) * a)
结果是28.999999996,转换为int是28
var xx float32
xx = 0.29
fmt.Println(xx * 100)
结果是29,转换为int是29您可能会发现,了解一下
常量
在go中的表达方式非常有用。特别是在这种情况下,由于原始代码将a
与整数相乘,因此该常量将转换为和int
,以实现兼容性。谢谢你的链接,我现在会读到的
var xx float32
xx = 0.29
fmt.Println(xx * 100)