how to solve this?

Write your question here.

Approximating the square root

Implement the sqrt function. The square root of a number, num, can be approximated by repeatedly performing a calculation using the following formula :

nextGuess = (lastGuess + (num / numGuess)) /2

The initial guess can be any positive value (e.g., 1). This value will be the starting vale for lastGuess. If the difference between nextGuess and lastGuess is less than a very small number, such as 0.0001, you can claim that nextGuess is the approximated square root of num. If not, nextGuess becomes the lastGuess and the approximation process continues.

Write your question here.

Ooh, this sounds like a fun game!

I'll start... who scored the final goal in the 1971 FA Cup final?
numGuess????

nextGuess = (lastGuess + (num/lastGuess)) /2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>

int main()
{
	int num;
	double lastGuess(1); //  inital guess
	double nextGuess(0);
	std::cin >> num;
	nextGuess = (lastGuess + (num/lastGuess))/2;
	while( (nextGuess - lastGuess) > 0.0001  || (nextGuess - lastGuess) < -0.0001 )
	{
		lastGuess = nextGuess;
		nextGuess = (lastGuess + (num/lastGuess))/2;
	}

	std::cout << nextGuess;
	std::cin.get();

	return 0;
}
Topic archived. No new replies allowed.