// 数的三次方(给出浮点数n) // AcWing 790 #include <stdio.h> double n; int main() { scanf("%lf", &n); double l = -100, r = 100; while (r - l > 1e-8) { double mid = (l + r) / 2; if (mid * mid * mid <= n) l = mid; else r = mid; } printf("%lf\n", l); return 0; }
while (r - l > 1e-8)
浮点数运算会出现精度错误(误差)。
利用枚举(for (int i = 1; i <= 100; i++))优化:
// 数的三次方(给出浮点数n) // AcWing 790 #include <stdio.h> double n; int main() { scanf("%lf", &n); double l = -100, r = 100; for (int i = 1; i <= 100; i++) { double mid = (l + r) / 2; if (mid * mid * mid <= n) l = mid; else r = mid; } printf("%lf\n", l); return 0; }
练习:
// 洛谷P1163 银行贷款 #include <stdio.h> #include <math.h> double a, b, c; int main() { scanf("%lf %lf %lf", &a, &b, &c); double l = 0, r = 1000; while (l < r - 1e-4) { double mid = (l + r) / 2; double w = a; // 未还的钱 for (int i = 0; i < c; ++i) // 模拟还钱过程。 w = w - b + w * (mid / 100); if (w < 0.0001) l = mid; else r = mid; } printf("%0.1f\n", round(l * 10) / 10); return 0; }
标签:二分,lf,int,double,浮点数,mid,三次方,100 From: https://www.cnblogs.com/gjkt2001/p/17280653.html