点击查看代码
#include<cstdio>
#include<cmath>
#pragma warning(disable:4996)
/*
装水问题:
有一个从侧面看去是半圆的储水装置,该半圆的半径是R,要求往里面装入高度为h的水,
使水的侧面积S1与整个半圆面积S2的比例为r。给定R和r,求h
*/
const double PI = acos(-1.0);
const double eps = 1e-5; //精度要求eps是10^-5
double f(double R, double h) {
//按题目说明画一幅图,计算一些三角形相关公式,即可得到以下公式
double alpha = 2 * acos((R - h) / R);
double L = 2 * sqrt(R * R - (R - h) * (R - h));
double S1 = alpha * R * R / 2 - L * (R - h) / 2;
double S2 = PI * R * R / 2;
return S1 / S2; //按照给定的mid值计算的r1
}
double solve(double R, double r) {
double left = 0, right = R, mid = 0; //[left,right]=[0,R]
while (right - left > eps) {
mid = left + (right - left) / 2; //mid就是要求的水面高度h
if (f(R, mid) > r) { //记r1=f(R, mid),如果r1>r说明r1过高,因此要减小r1,进入[left,mid]区间查找
right = mid;
}
else { //如果r1<=r说明r1过低,因此要增加r1,进入[mid,right]区间查找
left = mid;
}
}
return mid; //返回符合精度要求的mid,mid就是h的值
}
int main() {
//输入R、r
//调用solve(R,r);
//输出h
return 0;
}