Thread: Square root function compiles but doesn't work

  1. #1
    Registered User
    Join Date
    Oct 2013
    Posts
    9

    Square root function compiles but doesn't work

    I am writing a program to find the square root of a number. I am using the Newton-Raphson method..Just to clarify a bit of the code.. fabs(1/(x+1)) < 0.001 is to check for relative error..

    EXAMPLE: for user entry of 100 if the iteration process ends in 10.055 the answer will return as 10 which is correct. But it isn't doing that.

    It compiles I then proceed to run it..prompts me "Enter a number to find the square root of: I type 100 then hit enter...

    "The square root of 100 is -1077834936"

    Lol could you give me a bit of guidance here..thanks. My first time writing a program from complete scratch.

    And I know there is a sqrt() function...just wanted to write my own.

    Thanks a lot
    Code:
    #include <stdio.h>
    #include <math.h>
     
    double mysqrt(double a);
     
    int main()
    {
     double a, result;
     
     printf("Enter a number to find the square root of: ");
     scanf("%d", &a);
     
     result = mysqrt(a);
     
     printf("The square root of %d is %d \n", a, result);
     
    return 0;
    }
    double mysqrt(double a)
    {
     double x, new_x;
     
     for(x=2; x != a;)
     {
       new_x=(x+1);
       new_x=(0.5*(x+(a/x)));
       x=new_x;
     
       if(fabs(1/(x+1))<0.001)
       {
        return new_x;
       }
     }
    }

  2. #2
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    The scanf() and printf() calls are using %d with floating point variables. That yields undefined behaviour. Use %f or %g formats instead.

    It doesn't help that your mysqrt() function can fall off the end (no return statement if the for loop terminates).

    If you had turned up compiler warnings, your compiler would probably have complained bitterly and given you an idea of where the problems are.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Making my own square root function
    By Alexthunder in forum C++ Programming
    Replies: 2
    Last Post: 02-02-2006, 07:36 PM
  2. this code compiles, but doesn't work how it should
    By Leeman_s in forum C++ Programming
    Replies: 10
    Last Post: 09-10-2002, 05:31 PM
  3. square root function
    By Unregistered in forum C Programming
    Replies: 8
    Last Post: 05-19-2002, 03:11 AM
  4. my function doesn't work! it should work
    By Unregistered in forum C Programming
    Replies: 13
    Last Post: 05-02-2002, 02:53 PM

Tags for this Thread