How to calculate an int value and an float64 value in Golang?

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

How to calculate an int value and an float64 value in Golang?

问题

在上面的代码中,我无法理解为什么声明 a = int(b) 没有将 b 的值转换为 int。此外,如果我们可以完全省略这行代码并获得相同的结果,那么这样做的意义是什么?

package main

import "fmt"

func main() {
    a, b := 10, 5.5
    a = int(b)
    fmt.Println(float64(a) + b)
}

非常感谢!

英文:

On the following code I could not understand why the declaration a = int(b) didn't convert the value of b to int. Also, what is the point in doing so if we can achieve the same result omitting this line entirely anyways?

package main

import "fmt"

func main() {
	a, b := 10, 5.5
	a = int(b)
	fmt.Println(float64(a) + b)
}

Thanks a lot!

答案1

得分: 1

a, b := 10, 5.5 这行代码中,将值10赋给了变量a,默认类型为int,将值5.5赋给了变量b,默认类型为float64点击这里查看详情

然后 a = int(b) 这行代码将变量b的整数值赋给了a,即5。如果你不需要保留a的先前值,那么这两行代码可以简化为以下形式,得到相同的结果:

package main

import (
	"fmt"
)

func main() {
	b := 5.5
	a := int(b)
	fmt.Println(float64(a) + b) //输出:10.5
}

fmt.Println(float64(a) + b) 你不能对不同类型的值进行运算,所以你需要将a转换为float64类型,然后进行运算。如果将结果赋给另一个变量,那么结果也将是float64类型。

英文:

a, b := 10, 5.5
In this line, value 10 is assigned to the a with default type int and value 5.5 is assigned to the b with default type float64. tour here

then a = int(b) this line get integer value of b, that is 5 and assigned to a. If you don't need a's previous value then those two line can be write as follow and get same result.

package main

import (
	"fmt"
)

func main() {
	b := 5.5
	a := int(b)
	fmt.Println(float64(a) + b) //Output: 10.5
}

fmt.Println(float64(a) + b) you can not do operations with different types. that's why you need to convert a to float64 and do the operation. result also a float64 if you assigned it to another variable.

答案2

得分: 0

使用:

a = int(b)

a 变成了 5。所以:

float64(a) + b

变成了 10.5,因为 a=5b=5.5

英文:

With:

a=int(b)

a becomes 5. So:

float64(a)+b

becomes 10.5, because a=5 and b=5.5

答案3

得分: -1

package main

import "fmt"

func main() {
    a, b := 10, 5.5
    a = int(b)
    fmt.Println(float64(a) + b, a)
}

输出

10.5 5

看起来它将b转换为int -> 5 -> a = a + b = 5 + 5.5 = 10.5

这里将b强制转换为int,并将该值放入a中。

如果你想改变b的值,你应该这样做 b = int(b)

英文:
package main

import "fmt"

func main() {
    a, b := 10, 5.5
    a = int(b)
    fmt.Println(float64(a) + b, a)
}

Outputs

10.5 5

It seems like it is converting b to int -> 5 -> a = a+b = 5 + 5.5 = 10.5

Here b is typecasted to int and putting that value in a.

If you need to change the value of b you should do b = int(b).

huangapple
  • 本文由 发表于 2021年8月7日 22:05:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/68693063.html
匿名

发表评论

匿名网友

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

确定