Operator precedence in Go in formula V = 4/3πr3

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

Operator precedence in Go in formula V = 4/3πr3

问题

尝试设置球体体积的公式 V = 4/3πr3

我编写了 V = 4 / 3 * math.Pi * math.Pow(r, 3) 而不是 V = (4 * math.Pi * math.Pow(rˆ3)) / 3

我知道需要考虑运算符的优先级,但在这种情况下,我不清楚它可能会干扰所期望的结果,毕竟除了 */math.Pow 之外没有其他运算符。

英文:

Trying to set the formula of the volume of a sphere V = 4/3πr3

I coded V = 4 / 3 * math.Pi * math.Pow(r, 3) but not V = (4 * math.Pi * math.Pow(rˆ3)) / 3.

I get that there is operator precedence to be considered, but in this situation, I don't see where it may interfere on the desired result, afterall, there are no other operators besides *, / and math.Pow.

答案1

得分: 1

我相信你想要的是以下内容:

V = 4.0 / 3.0 * math.Pi * math.Pow(r, 3)

正如JimB所说,默认情况下,4 / 3 将进行整数除法,并且会有显著的四舍五入。你可以通过指定数据类型为 4.0 / 3.0 来强制进行浮点除法。

英文:

I believe what you want is as follows:

V = 4.0 / 3.0 * math.Pi * math.Pow(r, 3)

As JimB stated by default 4 / 3 will be an integer division as and such will round significantly. You can force a float division by specifying the data type with 4.0 / 3.0.

答案2

得分: 0

这是一个计算球体体积的示例代码:

package main

import (
	"fmt"
	"math"
)

func volume(radius float64) float64 {
	return 4.0 / 3.0 * math.Pi * math.Pow(radius, 3)
}

func main() {
	fmt.Println(volume(5.0))
}

输出结果为:

523.598775598299
英文:

Here is a sample code to find the volume of sphere :

package main

import (
	"fmt"
	"math"
)

func volume(radius float64) float64 {
	return 4.0 / 3.0 * math.Pi * math.Pow(radius, 3)
}

func main() {
	fmt.Println(volume(5.0))
}

Output:

523.598775598299

huangapple
  • 本文由 发表于 2021年8月12日 01:37:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/68746618.html
匿名

发表评论

匿名网友

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

确定