#include<stdio.h>
main()
{
//input
int num ;
while( 1 )
{
scanf("%d", &num );
int i = 1;
int temp = 1;
int low = 1;
int high = num;
for ( ; i <= num && i >= 1 && low <= high; )
{
temp = i*i;
if ( temp == num )
{
printf ("%d = %d*%d\n", num, i, i );
break ;
}
else if( temp < num )
{
low = i;
}
else
{
high = i;
}
temp = i;
i = ( low + high )/2;
if ( temp == i )
{
low = low + 1;
i = ( low + high )/2;
}
}
if (i > num || i < 1 || low > high )
printf("%d has no sqrt:(\n", num);
}
}
发现的问题:
1 c语言中的float转int是下取整的,座椅在计算i时,会遇到i固定不懂的情况,此时需要将low加1(或者,当采取从大到小的查找顺序时,减1),并且要重新计算i值,否则会进入无限循环
2 在不能找到平方根的时候,需要输出提示信息,此时在退出查找循环后需要判断是否找到了根,组合条件为:
i > num || i < 1 || low > high