#include <iostream>
#include <limits>
#include <cmath>
using namespace std;
int main()
{
int number;
cout << "Enter the number whose sqare root needs to be calculated";
cin >> number;
cout << "Square root of " << number << " is " << (int)sqrt((float)number) << " OR " << sqrt((float)number) << endl;
if( (int)sqrt((float)number) == sqrt((float)number) )
cout << "The number is a perfect sqaure";
else
cout << "The number is not a perfect square";
//To find the nearest perfect square if the number entered
// is not a perfect square?
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我希望我所做的检查完美的正方形是可以的,但此外我想找出最接近完美正方形的数字,如果输入的数字不是一个完美的正方形任何想法
lee*_*ade 11
实际上,这是更好的答案:
int number = 13;
int iRoot = static_cast<int>(sqrt(static_cast<float>(number)) + .5f);
Run Code Online (Sandbox Code Playgroud)
你不需要检查ceil或其底板是否更大,做一个简单的回合就可以了.
sqrt(13)是3.6,当你添加.5强制转换为4. sqrt(12)是3.46,当你添加.5强制转换为3.(我们试图舍入,这就是我们添加.5的原因).正如你所看到的,当数字更接近更高的根时,它会给你一个大于.5的小数; 当数字更接近较低值的根时,小数小于.5,就这么简单!
首先找到根的地板和天花板:
float root = sqrt((float)number);
int floor = (int)root;
int ceil = floor + 1
Run Code Online (Sandbox Code Playgroud)
然后检查哪个更接近ceil * ceil和floor * floor.