题解 | #求解立方根#
求解立方根
http://www.nowcoder.com/practice/caf35ae421194a1090c22fe223357dca
二分法分情况讨论
#include <iostream> #include <algorithm> using namespace std; int main() { double num = 0; cin >> num; double t = num; int sign = 1; if (num == 0 || num == 1) { printf("%.1f", num); return 0; } if (num < 0) { num = abs(num); sign = -1; } double left = 0, right = 0; if (num < 1) { left = 0; right = 1; } else { left = 1; right = num; } double mid = left + (right - left) / 2.0; while (abs(mid*mid*mid - num) > 0.001) { if (mid*mid*mid < num) left = mid; else right = mid; mid = left + (right - left) / 2.0; } printf("%.1f", sign * mid); return 0; }