C++ smart square to achieve the code

  • 2020-04-01 23:27:15
  • OfStack

You could guess a number, like 1.5, and divide 2 by that number. If we guess correctly, the result of division must be the same as the number we guessed. The better we guess, the closer we get to the division.

According to this principle, as long as we take the middle value of the number of guesses and the feedback number of trial division as the new guess number, it must be closer to the answer! This method of calculation is called the iterative method.


 double n = 2;
 double a = 0;
 double b = n;
 while(fabs(a-b)>1E-15)  //When the calculated to number and guess number are within a certain error output guess number
 {
  a = (a+b)/2;   //The number guessed is half of n
  b =  n/a;      
 }
 printf("%fn", a);


Related articles: