--Originally published at my programming blog
So for this WSQ I needed to make a function that asked the user for a number and then return a floating point in which it calculated the square root of the number the user entered, but the square root needs to be calculated with the Babylonian method.
First, here’s a picture of the Babylonia method (so you can have an idea of what I did in my code):
(Obtained from Wikipedia)
Also check this tutorial, it helped me a lot!
So this is what I did:
- I included the cmath library because I’m also going to print the square root of the number to check if the code is correct.
- I made a function (a float) called SquareRoot and in the parameters I included the double x (which will be the number the user will enter in the int main).
- Then I made a double called Error and I equaled it to 0.0001.
- Then for the Babylonian method you need to have a reference number, so I declared the double y which I assigned to the value of the double x.
- Then I did a while loop that while the double y minus x over y is bigger than the error I declared earlier this would repeat: I wrote the formula for the Babylonian method, that is that y will be equal to y plus x over y and that answer over 2. (This will be an intermediate result of the square root).
- Then once the condition of the while loop doesn’t happen the function will print “The final result is” and then return the value of y.
- Finally in the int main, I ask the user for a number, which is the declared double x and then call the function.
- After all this I print Continue reading "Babylonian method"