将Go中的uint8转换为float32。

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

Go uint8 to float32

问题

我正在尝试学习Go语言,并且正在开发一个雨强度工具。对于这个工具,我需要进行如下计算:

var intensity float32
intensity = 10^((value−109)÷32)

其中,value是一个取值范围为0到255的uint8类型的变量,而intensity是一个float32类型的变量。

然而,Go告诉我:

无法将10 ^ (value - 109) / 32 (类型为uint8)分配给float32类型

我该如何解决这个问题?

英文:

I'm trying to learn Go and working on a rain intensity tool.
For this tool I have to make a calculation like this:

var intensity float32
intensity = 10^((value−109)÷32)

The value is an uint8, ranging from 0 to 255. The intensity variable is a float.

However, Go tells me that

> cannot use 10 ^ (value - 109) / 32 (type uint8) as type float32 in assignment

How can I solve this?

答案1

得分: 3

  1. Go语言中没有÷运算符,^是按位异或运算符,你需要使用math包中的Pow函数。
  2. Go语言对类型转换非常严格,在许多情况下不允许隐式类型转换(例如无符号整数到浮点数的转换是无效的),所以你需要使用type(expr)来显式地进行转换,例如float32(1)

因此,代码可以这样写:

intensity := float32(math.Pow(10, float64((value - 109) / 32)))
// - 或者 -
intensity := float32(math.Pow10(int((value - 109) / 32)))
英文:
  1. There is no ÷ operator in Go and ^ is a bitwise XOR, you need to use Pow functions from math package
  2. Go is very strict about type conversions, so it disallows implicit type conversions in many cases (so unsigned integer to floating point is not valid), so you need explicitly convert it with type(expr), i.e. float32(1)

That said:

intensity = float32(math.Pow(10, float64((value - 109) / 32)))
// - OR -
intensity = float32(math.Pow10(int((value - 109) / 32)))

huangapple
  • 本文由 发表于 2017年9月8日 23:16:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/46119678.html
匿名

发表评论

匿名网友

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

确定