可能重复:
确定输入是否是完美正方形的好算法是什么?
我希望用最短最简单的方法来检查数字是否是C#中的完美平方
一些完美的正方形:
1, 4, 9, 16, 25, 36, 49, 64, 81, 100, ......
Run Code Online (Sandbox Code Playgroud)
Øyv*_*hen 40
可能检查数字的平方根是否有任何小数部分,或者它是否是整数.
在实现方面,我会考虑这样的事情:
double result = Math.Sqrt(numberToCheck);
bool isSquare = result%1 == 0;
Run Code Online (Sandbox Code Playgroud)
isSquare现在应该true适用于所有广场,以及false所有其他广场.
这是检查平方根是否为整数的变体:
bool IsPerfectSquare(double input)
{
var sqrt = Math.Sqrt(input);
return Math.Abs(Math.Ceiling(sqrt) - Math.Floor(sqrt)) < Double.Epsilon;
}
Run Code Online (Sandbox Code Playgroud)
Math.Ceiling将向上舍入到下一个整数,而Math.Floor将向下舍入.如果它们是相同的,那么你有一个整数!
这也可以写成oneliner:
if (int(Math.Ceiling(Math.Sqrt(n))) == int(Math.Floor(Math.Sqrt(n)))) /* do something */;
Run Code Online (Sandbox Code Playgroud)
public bool IsPerferctSquare(uint number)
{
return (Math.Sqrt(number) % 1 == 0);
}
Run Code Online (Sandbox Code Playgroud)