可能是重复问题:
有没有一种好的算法来确定输入是否为完全平方数?
我想要在C#中检查一个数是否为完全平方数的最短和最简单的方法。
一些完全平方数:
1, 4, 9, 16, 25, 36, 49, 64, 81, 100, ......
可能是重复问题:
有没有一种好的算法来确定输入是否为完全平方数?
我想要在C#中检查一个数是否为完全平方数的最短和最简单的方法。
一些完全平方数:
1, 4, 9, 16, 25, 36, 49, 64, 81, 100, ......
可能是在检查该数字的平方根是否有小数部分,或者它是否为整数。
在实现上,我会考虑像这样:
double result = Math.Sqrt(numberToCheck);
bool isSquare = result%1 == 0;
isSquare
现在应该对所有的正方形返回true
,对于其他所有图形返回false
。
bool IsPerfectSquare(double input)
{
var sqrt = Math.Sqrt(input);
return Math.Abs(Math.Ceiling(sqrt) - Math.Floor(sqrt)) < Double.Epsilon;
}
Math.Ceiling
方法会向上舍入为最接近的整数,而 Math.Floor
方法则向下舍入。如果两者相同,则结果为整数!
这也可以写成一行代码:
if (int(Math.Ceiling(Math.Sqrt(n))) == int(Math.Floor(Math.Sqrt(n)))) /* do something */;
Math.Ceiling()
和Math.Floor()
返回一个双精度值,因此您可能会遇到问题。相反,进行浮点比较:if (Math.Abs(val1 - valu2) < Double.Epsilon) { ... }
- michael< Double.Epsilon
而不是> 0
? - j.i.h. public bool IsPerferctSquare(uint number)
{
return (Math.Sqrt(number) % 1 == 0);
}
public bool IsPerfectSquare(int num)
{
int root = (int)Math.Sqrt(num);
return (int) Math.Pow(root,2) == num;
}