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