如何计算 C# 中的幂?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1366584/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I calculate power-of in C#?
提问by davethecoder
I'm not that great with maths and C# doesn't seem to provide a power-of function so I was wondering if anyone knows how I would run a calculation like this:
我不太擅长数学,而且 C# 似乎没有提供强大的功能,所以我想知道是否有人知道我将如何运行这样的计算:
var dimensions = ((100*100) / (100.00^3.00));
采纳答案by Paul Turner
回答by Daniel Brückner
You are looking for the static method Math.Pow()
.
您正在寻找静态方法Math.Pow()
。
回答by AakashM
The function you want is Math.Pow
in System.Math
.
你想要的功能Math.Pow
在System.Math
.
回答by Christopher Aicher
Do not use Math.Pow
不使用 Math.Pow
When i use
当我使用
for (int i = 0; i < 10e7; i++)
{
var x3 = x * x * x;
var y3 = y * y * y;
}
It only takes 230 ms whereas the following takes incredible 7050 ms:
它只需要 230 毫秒,而以下需要惊人的 7050 毫秒:
for (int i = 0; i < 10e7; i++)
{
var x3 = Math.Pow(x, 3);
var y3 = Math.Pow(x, 3);
}
回答by prosti
Math.Pow()
returns double
so nice would be to write like this:
Math.Pow()
double
这么好的回报是这样写的:
double d = Math.Pow(100.00, 3.00);
回答by Mumtaz Cheema
Following is the code calculating power of decimal value for RaiseToPower for both -ve and +ve values.
以下是计算 -ve 和 +ve 值的 RaiseToPower 十进制值的幂的代码。
public decimal Power(decimal number, decimal raiseToPower)
{
decimal result = 0;
if (raiseToPower < 0)
{
raiseToPower *= -1;
result = 1 / number;
for (int i = 1; i < raiseToPower; i++)
{
result /= number;
}
}
else
{
result = number;
for (int i = 0; i <= raiseToPower; i++)
{
result *= number;
}
}
return result;
}
回答by jeromej
For powers of 2:
对于 2 的幂:
var twoToThePowerOf = 1 << yourExponent;
// eg: 1 << 12 == 4096
回答by H. Pauwelyn
I'm answering this question because I don't find any answer why the ^
don't work for powers. The ^
operator in C#is an exclusive oroperator shorten as XOR. The truth tableof A ^ B
shows that it outputs true whenever the inputs differ:
我正在回答这个问题,因为我没有找到任何答案为什么^
不为权力工作。所述^
在C#操作者是一个异或操作者缩短为XOR。该真值表的A ^ B
显示,每当输入不同则输出真:
| Input | |
| A | B | Output |
| - | - | ------ |
| 0 | 0 | 0 |
| 0 | 1 | 1 |
| 1 | 0 | 1 |
| 1 | 1 | 0 |
Witch means that 100 ^ 3
does this calculation under the hood:
女巫意味着100 ^ 3
在引擎盖下进行此计算:
hex binary
100 = 0110 0100
3 = 0000 0011
--- --------- ^
103 = 0110 0111
With is of course not the same as Math.Pow(100, 3)
with results to one million. You can use that or one of the other existing answers.
with当然不等于Math.Pow(100, 3)
with结果到100万。您可以使用该答案或其他现有答案之一。
You could also shorten your code to this that gives the same result because C# respects the order of operations.
你也可以将你的代码缩短为这样的,因为 C# 尊重操作顺序。
double dimensions = 100 * 100 / Math.Pow(100, 3); // == 0.01