Thread: Squareroot User Defined Function

  1. #1
    Registered User
    Join Date
    Jan 2009
    Posts
    26

    Squareroot User Defined Function

    Code:
    #include<stdio.h>
    
    float SR(float s)
    {
          float a, b, c;
          
           a = 1;
           b = (a + s / a)/2;
           c = b - a;
           a = b;
          
          
          while(c*c>0.001){
                           
                           b = (a + s / a)/2;
                           return b;}
                           
          return b;
    }
    
    int main()
    {
        float x;
        
        printf("Please enter a number: ");
        scanf("%f", &x);
        
        printf("The square root of %f is %f", x, SR(x));
        scanf("%d");
        
    }
    What is wrong with my code? When I enter '9', I get '3.4' as the output which is wrong. It should display '3'.

  2. #2
    The larch
    Join Date
    May 2006
    Posts
    3,573
    Code:
          while(c*c>0.001){
                           
                           b = (a + s / a)/2;
                           return b;}
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

  3. #3
    Chinese pâté foxman's Avatar
    Join Date
    Jul 2007
    Location
    Canada
    Posts
    404
    Also, as far as I can see, your loop condition is constant, so you'll either have an infinite loop (if you don't have any return statement in it like you currently do) or you'll never enter your loop. So you should update c in your loop... and remove that return statement in it, it has nothing to do there.

    Also, I can see that you are using the "Babylonian method". You might have slow convergence if you are trying to compute the square root of large number since you don't approximate the value of s as the first step in your algorithm but instead is using 1.
    I hate real numbers.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Getting an error with OpenGL: collect2: ld returned 1 exit status
    By Lorgon Jortle in forum C++ Programming
    Replies: 6
    Last Post: 05-08-2009, 08:18 PM
  2. Replies: 14
    Last Post: 03-02-2008, 01:27 PM
  3. Replies: 28
    Last Post: 07-16-2006, 11:35 PM
  4. errors initializing D3D
    By Vacation Guy in forum C++ Programming
    Replies: 3
    Last Post: 08-07-2005, 12:20 PM
  5. Contest Results - May 27, 2002
    By ygfperson in forum A Brief History of Cprogramming.com
    Replies: 18
    Last Post: 06-18-2002, 01:27 PM