题解 | #求解立方根#
求解立方根
http://www.nowcoder.com/practice/caf35ae421194a1090c22fe223357dca
二分
#include <stdio.h> float getValWhenMore0(float left, float right, float val) { float mid = (left + right) / 2.0; while(1){ if(mid * mid * mid > val){ if(mid * mid * mid - val <= 0.01){ return mid; } else{ right = mid; mid = (left + right) / 2.0; } } else if(mid * mid * mid < val){ if(val - mid * mid * mid <= 0.01){ return mid; } else{ left = mid; mid = (left + right) / 2.0; } } else{ return mid; } } } float getValWhenLess0(float left, float right, float val) { float mid = (left + right) / 2.0; while(1){ if(mid * mid * mid < val){ if(val - mid * mid * mid <= 0.01){ return mid; } else{ right = mid; mid = (left + right) / 2.0; } } else if(mid * mid * mid > val){ if(mid * mid * mid - val <= 0.01){ return mid; } else{ left = mid; mid = (left + right) / 2.0; } } else{ return mid; } } } int main() { float val; while(scanf("%f", &val) != EOF){ float mid, left = 0.0, right = val; if(val >= 1.0){ mid = getValWhenMore0(left, right, val); } else if(val <= -1.0){ mid = getValWhenLess0(left, right, val); } else if(val > 0 && val < 1.0){ left = val; right = 1.0; mid = getValWhenMore0(left, right, val); } else if(val > -1.0 && val < 0.0){ left = val; right = -1.0; mid = getValWhenLess0(left, right, val); } printf("%0.1f\n", mid); } }