我有一个功能:C#isPowerOf功能
static bool isPowerOf(int num, int power)
{
double b = 1.0/power;
double a = Math.Pow(num, b);
Console.WriteLine(a);
return a == (int)a;
}
我插入用于分析的打印功能。
如果我调用该函数:
isPowerOf(25, 2)
它,因为5^2
等于25 返回true但是,如果我叫16807,这是7^5
,接下来的路:
isPowerOf(16807, 5)
在这情况下,它打印'7',但a == (int)a
返回false。
你能帮忙吗?谢谢!
强制链接到[每个计算机科学家应该知道的浮点算术](http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html) – AakashM 2012-07-06 09:47:12
每个人都会建议更好浮点比较,但IMO问题的根源在于这里的算法。 – harold 2012-07-06 09:48:36