Jho*_*ith -5 c++ square-root bisection
据我所知,二分是缩小您的搜索范围并在间隔内达到特定值。请给我一个关于如何制作通用代码以找到平方根的示例。我认为采用三个变量的方式是低、中、高。高 = 用户输入,低 = 0,中(低 + 高)/2,问题是如何更改值。
#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;
}
Run Code Online (Sandbox Code Playgroud)