Go – 科学计数法乘法

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

Go - multiple by scientific notation

问题

我正在寻找一个在Go语言中计算1 * 10 ^ x的示例。

例如,1 * 10 ^ 18给出的输出是24,而不是1000000000000000000

基本上,我想要能够执行x * 1e{y}

英文:

I'm looking for an example of how to calculate 1 * 10 ^ x in golang.

For example 1 * 10 ^ 18 gives me the output of 24 instead of 1000000000000000000

essentially I'd like to be able to perform x * 1e{y}

答案1

得分: 2

在Go语言中,^用于按位异或运算。

你可以从这里了解Go语言的运算符。Go语言运算符

你可以使用Go语言中的math包执行上述操作。

package main

import (
	"fmt"
	"math"
)

func main() {
	x := 1.0
	res := x * math.Pow(10, 18)
	fmt.Printf("%f", res)
}
英文:

In GoLang ^ is used for bitwise XOR.

You can learn about GoLang operators from here. GoLang Operators

You can perform the above operation using the math in GoLang.

package main

import (
	"fmt"
	"math"
)

func main() {
	x := 1.0
	res := x * math.Pow(10, 18)
	fmt.Printf("%f", res)
}

答案2

得分: 0

我认为其他回答已经指出了这一点,^ 是按位异或运算符。当你执行 1 * 10 ^ 18 时,实际上是在计算 10 ^ 18。由于 10 在二进制中表示为 01010,18 在二进制中表示为 10010,所以 10 ^ 18 的结果是 11000 或者 24。

要得到你想要的结果,你应该这样做:

package main

import (
    "fmt"
    "math"
)

func main() {
    multiplier := 1.0
    exponent := 18
    result := multiplier * math.Pow10(exponent)
    fmt.Printf("%f * 10 ^ %d = %f", multiplier, exponent, result)
}

在这个示例中,工作是由 math 包中的 Pow10 函数完成的。它产生一个等于给定函数值的 10 的幂的值。然后我们将这个值乘以乘数以获得结果。运行这段代码将得到以下结果:

1.000000 * 10 ^ 18 = 1000000000000000000.000000
英文:

I think other answers have already pointed this out, but ^ is bitwise XOR. When you do 1 * 10 ^ 18, you're essentially evaluating 10 ^ 18. Since, 10 evaluates to 01010 in binary and 18 evaluates to 10010 in binary, 10 ^ 18 would result in 11000 or 24.

To get the result you want, you should do:

package main

import (
    "fmt"
    "math"
)

func main() {
    multiplier := 1.0
    exponent := 18
    result := multiplier * math.Pow10(exponent)
    fmt.Printf("%f * 10 ^ %d = %f", multiplier, exponent, result)
}

In this example, the work is being done by the Pow10 function in the math package. It produces a value equal to ten to the power of the value given to the function. Then we multiply this by the multiplier to get the result. Running this code would yield the following:

1.000000 * 10 ^ 18 = 1000000000000000000.000000

huangapple
  • 本文由 发表于 2022年9月6日 05:54:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/73614958.html
匿名

发表评论

匿名网友

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

确定