# Thread: Squareroot User Defined Function

1. ## 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. Code:
```      while(c*c>0.001){

b = (a + s / a)/2;
return b;}```

3. 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.

Popular pages Recent additions