我正在测试一个小的C#程序片段:
short min_short = (short)(int)-Math.Pow(2,15);
short max_short = (short)(int)(Math.Pow(2, 15) - 1);
Console.WriteLine("The min of short is:{0};\tThe max of short is:{1}", min_short, max_short);
int min_int = (int)-Math.Pow(2, 31);
int max_int = (int)(Math.Pow(2, 31) - 1);
Console.WriteLine("The min of int is:{0};\tThe max of int is:{1}", min_int, max_int);
uint min_uint = 0;
uint max_uint = (uint)(Math.Pow(2, 32) - 1);
Console.WriteLine("The min of uint is:{0};\tThe max of uint is:{1}", min_uint, max_uint);
long min_long = (long)-Math.Pow(2, 63);
long max_long = (long)(Math.Pow(2, 63) - 1);
Console.WriteLine("The min of long is:{0};\tThe max of long is:{1}", min_long, max_long);
ulong min_ulong = 0;
ulong max_ulong = (ulong)(Math.Pow(2, 64) - 1);
Console.WriteLine("The min of ulong is:{0};\tThe max of ulong is:{1}", min_ulong, max_ulong);
输出结果为:
The min of ushort is:0; The max of ushort is:65535
The min of short is:-32768; The max of short is:32767
The min of int is:-2147483648; The max of int is:2147483647
The min of uint is:0; The max of uint is:4294967295
The min of long is:-9223372036854775808;The max of long is:-9223372036854775808
The min of ulong is:0; The max of ulong is:0
我怀疑这个错误是由Math.Pow()的函数引起的,这是返回的双重类型。
public static double Pow(
double x,
double y
)
所以,我的问题是:长型是否有类似的数学函数? 如何纠正上面程序片段中的错误。 非常感谢!
答案 0 :(得分:5)
您达到Math.Pow
限制。
您需要使用System.Numerics.BigInteger.Pow
。
答案 1 :(得分:0)
public static ulong Power(ulong A, ulong n)
{
ulong result = n;
for(ulong i = 0; i < A; i++)
{
result *= A;
}
return result;
}
static void Sample()
{
Console.WriteLine("Result: " + Power(12, 62));
}
输出 结果:552798227791872
答案 2 :(得分:-2)
public static long Power(long A, ulong n)
{
long result = 1; // if n==0,A^n==1
if (n>0)
{
do
{
result *= A;
n--;
} while (n>0);
}
return result;
}