The sqrt() function is a function we often use. Below I will introduce some of its usage and usage specifications in detail
Required header files
#include<math.h>
Function prototype
double sqrt(double x);
Function:
sqrt() is used to find the square root of a given value
Common usage errors
The open root of output 36
ignores that the return value of the sqrt() function is of double type. Cause an error
The solution is as follows: the
common canonical writing of the sqrt() function.
For example: We need to judge whether a number is prime or not, we only need to judge whether there is a divisible number between the radicals of 2 and n.
Wrong writing:
bool find(int n)
{
for(int i=2;i<=sqrt(n);i++)
{
if(n%i==0)
return false;
}
return true;
}
The above writing method is actually not recommended. Although I often write like this.
But in the process of doing a question, a bug occurred just because of this.
I changed to the correct writing method using the following safe writing
method:
bool find(int n)
{
int sql=(int)sqrt(1.0*n);//1.0*n的目的是 隐式转换成浮点数,开根号后再强制转换成整型
for(int i=2;i<=sql;i++)
{
if(n%i==0)
return false;
}
return true;
}