如何从big.Int中找到15%的值?

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

How to find 15% from big.Int

问题

我想要获取big.Int值的15%,我该如何做?

new(big.Int).Mul(totalValue, new(big.Int).Div(new(big.Int).SetUint64(15), new(big.Int).SetUint64(100)))

返回0

英文:

I'm want to get 15% of big.Int value, how can I do this?

new(big.Int).Mul(totalValue, new(big.Int).Div(new(big.Int).SetUint64(15), new(big.Int).SetUint64(100)))

returns 0

答案1

得分: 1

运算顺序在涉及除法的整数运算中非常重要。以以下代码为例:

int n = 200;

Console.WriteLine($"{n * (15 / 100)}");
Console.WriteLine($"{(n * 15) / 100}");

第一个 WriteLine 将打印出 0,而第二个将打印出 30。
尽管理论上两行代码应该产生相同的结果,因为乘法和除法是可结合的。如果你使用浮点数运算,它们实际上会产生相同的结果。

然而,在这种情况下,整数运算的工作方式有些不同。问题在于 15/100 在整数除法中得到的结果是 0。因此,如果先执行除法,结果将始终为 0。

英文:

Order of operations can be really important with integer arithmetic when division is involved. Take the following code for example

int n = 200;

Console.WriteLine($"{n * (15 / 100)}");
Console.WriteLine($"{(n * 15) / 100}");

The first WriteLine will print 0 and the second will print 30.
Even though both lines should theoretically yield the same result because multiplication and division are associative. And they would actually produce the same result if you were using floating point math.

However, in this case integer math works a little differently. The problem is 15/100 yields 0 with integer division. So if the division is performed first, the result will always be 0.

huangapple
  • 本文由 发表于 2022年10月11日 01:42:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/74018813.html
匿名

发表评论

匿名网友

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

确定