题解 | #求解立方根#
求解立方根
https://www.nowcoder.com/practice/caf35ae421194a1090c22fe223357dca
#include <stdio.h> #include <stdlib.h> #include <math.h> #define min(x,y)?x:y int main() { double num; scanf("%lf",&num); double numabs=fabs(num);//取输入值的绝对值,简化后续比较。 double dValue=numabs; double minCubeRoot=numabs; for(int i=0;i<30;i++) { double cubeRoot=0+0.1*i; double tmp=cubeRoot*cubeRoot*cubeRoot; if(tmp==numabs) { printf("%1.1lf",(cubeRoot*(num/numabs))); } else if(dValue>fabs(numabs-tmp))//当差值的绝对值最小时,即为立方根 { minCubeRoot=cubeRoot; dValue=numabs-tmp; } } printf("%1.1lf",(minCubeRoot*(num/numabs))); }