45 lines
1.0 KiB
C++
45 lines
1.0 KiB
C++
#include <iostream>
|
|
#include <iomanip>
|
|
#include <cmath>
|
|
#define f(x) ((x) * (x) - a) // 定義方程式 f(x)
|
|
|
|
using namespace std;
|
|
|
|
int main() {
|
|
|
|
double a;
|
|
cout << "平方根的數值 a= ";
|
|
cin >> a;
|
|
cout << "----------------------------------------"<< endl;
|
|
double c=sqrt(a);
|
|
double left = 0, right = 20; // 設定範圍
|
|
double b = 1e-10;
|
|
double mid;
|
|
int i = 0;
|
|
|
|
while ((right - left) > b) {
|
|
mid = (left + right) / 2.0;
|
|
i++;
|
|
printf("#%d [%f %f ]\n", i, left, right);
|
|
|
|
if (f(mid) == 0.0) {
|
|
cout << "根的近似值為: " << mid << " 且 f(x)= " << f(mid) << endl;
|
|
return 0;
|
|
}
|
|
|
|
if (f(left) * f(mid) < 0) {
|
|
right = mid; // 左邊
|
|
} else {
|
|
left = mid; // 右邊
|
|
}
|
|
}
|
|
cout << "-----------------------------------------"<< endl;
|
|
int d=((mid - c) / (c)) * 100 ;
|
|
if(d>0)
|
|
d=d;
|
|
else
|
|
d=-d;
|
|
cout << "sqrt("<< a <<"): " << sqrt(a) << " 誤差值為(%)" << d << endl;
|
|
return 0;
|
|
}
|