Golang how can I multiply a integer and a float

huangapple go评论82阅读模式
英文:

Golang how can I multiply a integer and a float

问题

我正在尝试调整图像的尺寸,但在编译时出现了"常量0.8截断为整数"的错误。这是我的代码:

b := img.Bounds()

heightImg := b.Max.Y  // 图像的高度(以像素为单位)
widthImg := b.Max.X   // 图像的宽度(以像素为单位)
const a = .80
height := int(heightImg * a) // 将高度减少20%
width := int(widthImg * a)  // 将宽度减少20%

// 调整图像的大小,第二个和第三个参数需要是int类型
new_img := imaging.Resize(img, width, height, imaging.Lanczos)

我对Go语言还不熟悉,但是这段代码给我报错:

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

有什么建议吗?

英文:

I am trying to resize the dimensions of an image but am getting a constant 0.8 truncated to integer error on compile . This is my code

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)

I am new to golang but this code right here gives me the error

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

any suggestions would be great

答案1

得分: 31

如果你想要将浮点数相乘,你需要将数字转换为浮点数:

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

If you want to multiply floats, you need to convert the number to a float:

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

答案2

得分: 1

以下是翻译好的内容:

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

结果为 28.999999999999996转换为整数为 28

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

结果为 29转换为整数为 29
英文:
var xx float64
xx = 0.29
fmt.Println(xx, xx * 100)

The result is 28.999999999999996, convert to int is 28

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

The result is 29, convert to int is 29

huangapple
  • 本文由 发表于 2017年5月4日 03:24:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/43768377.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定