sqrt定义,为什么是错的?
#include<stdio.h>void main()
{
printf("输入一个正整数:");
int sqrtes (int x);
int a,c;
scanf ("%d",&a);
c = sqrtes(a);
printf("sqrtes is %d\n",c);
}
int sqrtes (int x)
{
int low,mid,high,last;
low = 0;
high = x;
mid = ( ( low + high ) / 2 );
do
{
if ( mid * mid > x )
high = mid;
else
low = mid;
mid = ( ( low + high ) / 2 );
}while ( x = mid * mid );
return (mid);
}
本帖最后由 jackz007 于 2021-11-8 13:13 编辑
sqrt() 试试这个代码
#include <stdio.h>
double sqrtx(int n)
{
double d , e , x ;
for(e = 1.0 , x = 0.0 ; e > 1e-12 && x * x < n ; e /= 10.0) {
for( ; (x + e) * (x + e) < n ; x += e) ;
}
return x ;
}
int main(void)
{
printf("sqrt(0) = %lf\n" , sqrtx(0)) ;
printf("sqrt(1) = %lf\n" , sqrtx(1)) ;
printf("sqrt(2) = %lf\n" , sqrtx(2)) ;
printf("sqrt(3) = %lf\n" , sqrtx(3)) ;
printf("sqrt(4) = %lf\n" , sqrtx(4)) ;
}
编译、运行实况:
D:\00.Excise\C>g++ -o x x.c
D:\00.Excise\C>x
sqrt(0) = 0.000000
sqrt(1) = 1.000000
sqrt(2) = 1.414214
sqrt(3) = 1.732051
sqrt(4) = 2.000000
D:\00.Excise\C> mid类型改为float
页:
[1]