-5

Bisection is as far as i know narrowing your search and reach the specific value in interval. please give me a sample of that how to make a generic code to find square-root. the way i think is taking three variables low, mid, high. high = userinput, low = 0, mid (low + high) /2, problem is how to how to change values then.

4

2 回答 2

5
#include <iostream>
using namespace std;

int main() {
   int val;
   cout << "Enter the number: ";
   cin >> val;

   if( val< 0) {
      cout<< "According to my maths its not possible." << endl;
   } else {
      float low = 0, high = val;
      float mid = (low  + high)/2;
      int c = 0;

      while (c != 1) {
         if(mid * mid = val) {
            cout << "Square root is: " << mid <<endl;
            c = 1;
         } else {
            if(mid * mid > val) {
               high = mid;
               mid = (low + high)/2;
            } else {
               low = mid;
               mid = (low + high)/2;
            }
         }
      }
   }
   return 0;
}
于 2013-11-07T19:24:32.160 回答
0

可以说我们正在寻找sqrt(N)

如此处所述,您必须找到 LOW 和 HIGH 的平均值,如果平均值的平方大于N,我们将高值更改为我们刚刚找到的平均值,如果小于N,我们将更改为平均值的低值。我们重复这些步骤多次以满足所需的精度。

于 2013-11-07T19:23:11.090 回答