Golang如何乘以整数和浮点数

时间:2017-05-03 19:24:21

标签: 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 * 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)

任何建议都会很棒

2 个答案:

答案 0 :(得分:12)

如果要乘以浮点数,则需要将数字转换为浮点数:

height := int(float64(heightImg) * a) 
width := int(float64(widthImg) * a)

答案 1 :(得分:0)

var xx float64
xx = 0.29
fmt.Println(xx, xx * 100)

结果为28.999999999999996,转换为int为28

var xx float32
xx = 0.29
fmt.Println(xx * 100)

结果为29,转换为int为29