1. Newton's method

I have this code that should calculate the square root of a number useing newton's method.
It compiles and runs , but while I debug ,it doesn't give the right answer for most numbers (except for the roots of 4,16,25, 36 etc)thanks for any help !

Code:
```#include <stdio.h>
int squareRoot(int num,int ans,int tol);

int main(void)
{
int num,ans,tol,root;
printf("Enter the number you want squarerooted");
scanf("%d",&num);
printf("Enter your guess of the number's root");
scanf("%d",&ans);
printf("Enter the pretidetermined tolerance");
scanf("%d",&tol);
root = squareRoot(num,ans,tol);
printf("%d%d","The square root of ",num," is:",root);
}

int squareRoot(int num,int ans,int tol)
{
if((ans^2 - num <= tol))
return ans;
else
return (squareRoot(num,((ans^2 + num)/(2 * ans)),tol));
}```

2. First of all change your print statement to:
Code:
`printf("The square root of %d is: %d\n",num,root);`
No %s needed.

Second of all, I dont think ans^2 does what you think it does. You might want to read up on how to square a number. If you dont want to look it up, then just do ans*ans.

3. Thanks ! I did notice though when debugging ,and I enter say 50 for num , 7 for ans , and 0.01 for tol , it just returns 7.
Plus when I tried typeing in a double it didn't work the way I wanted, so I changed all the occurances of int to double , and then it wouldn't compile anymore

4. In C, the ^ operator stands for the XOR(exclusive or) operator. You want to write your own square routine such as "#define SQUARE(x) ((x) * (x))" or simply a * a.

5. Originally Posted by Cmuppet
Thanks ! I did notice though when debugging ,and I enter say 50 for num , 7 for ans , and 0.01 for tol , it just returns 7.
Plus when I tried typeing in a double it didn't work the way I wanted, so I changed all the occurances of int to double , and then it wouldn't compile anymore
That's because you can't use bitwise operators directly on floating point numbers. (^ is a bitwise operator, as described in the post above mine)

Quzah.

6. Thanks , it works now ! Thanks again

Popular pages Recent additions