英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论