#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2013
    Location
    Dhaka, Bangladesh
    Posts
    116
    Rep Power
    2

    Question Using Newton's method to compute square root of a value


    In this project, I am trying to create a program which would equate the square root of a provided positive integer using Newton's method. A screenshot to how this is done is attached to this post.
    x is the provided input, and y has an initial arbitrary value of 1. The program is supposed to terminate when the difference between the old value of y and the new value of y is less than the product of 0.00001 and y. Here's the code I have written:
    Code:
    #include <stdio.h>
    #include <math.h>
    
    int main(void)
    {
    	int x;
    	double y = 1, evaluation;
    		
    	printf("Enter a positive number: ");
    	scanf("%d", &x);
    	
    	do	{
    	evaluation = ((y + (x / y)) / 2);
    	y = evaluation;
    	} while (evaluation > (0.00001 * y));
    	
    	printf("\nSquare root: %lf", fabs(y));
    	
    	return 0;
    }
    But when executed, the program simply freezes after entering the input. The cursor drops to a new line and just keeps blinking. What am I doing wrong here?
    Attached Images
  2. #2
  3. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2013
    Location
    Saint-Petersburg, Russia
    Posts
    236
    Rep Power
    28
    Rather than explain you problem at once, I prefer to offer you debugging your program. This is quite important skill :)

    Or at least insert another printf inside the loop, printing out current values of variables. I think this will give you a hint.

    Funny enough, I added similar task to my website only two days ago:

    Square Root at http://codeabbey.com

    Though perhaps some hint could be necessary. Check your loop exiting condition very thoroughly.

    And get rid of "evaluation" variable since you assign it to y again.

    Really, think twice over this strange idea the new value of y is less than the product of 0.00001 and y - could it really happen in your code?

IMN logo majestic logo threadwatch logo seochat tools logo