题述:
求方程f(x)=2^x+3^x-4^x=0在[1,2]内的根。输入m(0<=m<=8),输出m位小数。
参考代码:
#include <iostream>
#include <cmath>
double f(double x) {
return pow(2, x) + pow(3, x) - pow(4, x);
}
double findRoot(double left, double right, int precision) {
double mid, root;
double error = pow(10, -precision);
while (right - left > error) {
mid = (left + right) / 2;
if (f(mid) == 0) {
return mid;
} else if (f(mid) * f(left) < 0) {
right = mid;
} else {
left = mid;
}
}
root = left + (right - left) / 2;
return root;
}
int main() {
int precision;
std::cout << "请输入要输出的小数位数(0 <= m <= 8):";
std::cin >> precision;
double left = 1.0;
double right = 2.0;
double root = findRoot(left, right, precision);
std::cout.precision(precision);
std::cout << "方程的根为:" << std::fixed << root << std::endl;
return 0;
}