2012-12-21 5 views
0

나는 newton-raphson 반복 기법을 사용하여 2,3,4,5의 제곱근을 찾는 간단한 C 프로그램을 작성했습니다. 이 코드는 2의 제곱근 만 찾아서 표시합니다. 그 후에 그것은 멈춘다. 이 코드로 문제를 알아낼 수 있습니다 : 당신이 사방 doublefloat를 교체 할 경우C 코드가 예상대로 실행되지 않음

# include<stdio.h> 

    float square(float x); 
    float absolutevalue(float x); 

int main(void) 
{ 
    printf("square root of 2 is %f\n", square(2)); 
    printf("square root of 3 is %f\n", square(3)); 
    printf("square root of 4 is %f\n", square(4)); 
    printf("square root of 5 is %f\n", square(5)); 

    return 0; 
} 

float square(float x) 
{ 
    float epsilon = 0.0000001; 
    float guess = 1; 

    while (absolutevalue(guess*guess - x) >= epsilon) 
     guess = ((x/guess) + guess)/2; 

    return guess; 
} 

float absolutevalue(float x) 
{ 
    if (x < 0) 
     x = -x; 

    return x; 
} 
+0

외부 연결로 사용할 때'square'는 예약 된 식별자입니다. – ouah

+15

엡실론이 너무 작 으면 float 유형의 유효 자릿수가 충분하지 않습니다. 빠른 수정을 위해 모든 float을 * double *로 대체하십시오. –

+1

[출력] (http://stacked-crooked.com/view?id=a9548fc448972258896a9e17cb43e8a5)을 보면'guess'의 값을 루프에 출력하면 문제를 아주 쉽게 볼 수 있습니다. –

답변

1

모든 것이 잘 작동합니다.

관련 문제