题解 | #求解立方根#穷举法
求解立方根
https://www.nowcoder.com/practice/caf35ae421194a1090c22fe223357dca
#include <iostream>
using namespace std;
int main() {
double num;
while (cin >> num) {
// 穷举法
bool isNeg = false;
double res = 0;
// 如果是0,则输出0
if (num == 0) {
cout << res << endl;
continue;
}
// 负数转为正数
if (num < 0) {
num *= -1;
isNeg = true;
}
// 大于0小于1,遍历区间需要修改
double left = 1.0;
double right = num;
if (num > 0 && num < 1) {
left = 0.1;
right = 1;
}
for (double i = left; i < right; i += 0.1) {
// i对应的三次方结果
double mul1 = i * i * i;
// 递增0.1后的三次方结果
double next = i + 0.1;
double mul2 = next * next * next;
// 如果输入在二者范围表示找到了结果区间
if (num >= mul1 && num < mul2) {
// 判断num离那个结果近,则结果选哪个
if (num - mul1 > mul2 - num) {
res = next;
} else {
res = i;
}
break;
}
}
// 把符号乘回来
if (isNeg) {
res *= -1;
}
cout << res << endl;
}
}
// 64 位输出请用 printf("%lld")
