【acwing】数的三次方根

数的三次方根

给定一个浮点数 n n n,求它的三次方根。

输入格式

共一行,包含一个浮点数 n n n

输出格式

共一行,包含一个浮点数,表示问题的解。

注意,结果保留 6 6 6 位小数。

数据范围

− 10000 ≤ n ≤ 10000 -10000 \le n \le 10000 10000n10000

输入样例:

1000.00

输出样例:

10.000000

第一种代码

#include
#include
using namespace std;
double n;
int main() {
	cin >> n;
	double l = -10000, r = 10000;
	while (r - l > 1e-8) {
		double mid = (l + r) / 2;
		if (pow(mid, 3) > n)r = mid;
		else l = mid;
	}
	printf("%.6lf", l);
	return 0;
}

知识点

实数二分

第二种代码

#include
#include
using namespace std;
double n;
int main() {
	cin >> n;
	//double pow(double x, double y);
	if (n < 0) {
		cout << "-";
		n = -n;
	}
	printf("%.6lf", pow(n, 1.0/3));
	return 0;
}

知识点

pow函数
头文件:#include
1.函数原型
pow() 函数用来求 x 的 y 次幂(次方),x、y及函数值都是double型 ,其原型为:
double pow(double x, double y);
2.注意事项
可能导致错误的情况:
如果底数 x 为负数并且指数 y 不是整数,将会导致 domain error 错误。
如果底数 x 和指数 y 都是 0,可能会导致 domain error 错误,也可能没有;这跟库的实现有关。
如果底数 x 是 0,指数 y 是负数,可能会导致 domain error 或 pole error 错误,也可能没有;这跟库的实现有关。
如果返回值 ret 太大或者太小,将会导致 range error 错误。

你可能感兴趣的:(c++,算法)