Problem Description
The WHU ACM Team has a big cup, with which every member drinks water. Now, we know the volume of the water in the cup, can you tell us it height?
The radius of the cup’s top and bottom circle is known, the cup’s height is also known.
Input
The input consists of several test cases. The first line of input contains an integer T, indicating the num of test cases.
Each test case is on a single line, and it consists of four floating point numbers: r, R, H, V, representing the bottom radius, the top radius, the height and the volume of the hot water.
Technical Specification
- T ≤ 20.
- 1 ≤ r, R, H ≤ 100; 0 ≤ V ≤ 1000,000,000.
- r ≤ R.
- r, R, H, V are separated by ONE whitespace.
- There is NO empty line between two neighboring cases.
Output
For each test case, output the height of hot water on a single line. Please round it to six fractional digits.
Sample Input
1
100 100 100 3141562
Sample Output
99.999024
题意:有一个圆台,知道下底半径r,上底半径R,台高H,里面热水体积V,求H;
看到H的范围,以及该题的精度,想到二分~
圆台体积公式为:
在[0,H]中二分求h,注意求不同h时R也不同;
设此时的R为x,
解得
代入即可~注意二分条件~
#include <iostream>
#include <cstdio>
#include <cmath>
using namespace std;
#define exp 1e-10
#define PI 3.1415926535
#define getV(r,R,h) PI*h*(R*R+r*r+r*R)/3.0
int main(){
int t;
scanf("%d",&t);
while(t--){
double r,R,H,V;
scanf("%lf %lf %lf %lf",&r,&R,&H,&V);
double left=0.0,right=H;
double mid=0.0,vTemp=0.0,RTemp=0.0;
while(right-left>exp){
mid=(left+right)/2.0;
RTemp=mid/H*(R-r)+r;
vTemp=getV(r,RTemp,mid);
if(fabs(vTemp-V)<exp){
break;
}
else if(vTemp>V){
right=mid-exp;
}
else{
left=mid+exp;
}
}
printf("%.6f\n",mid);
}
}
/*
1
100 100 100 3141562
*/
一题类似的二分:hdu 2199 Can you solve this equation?
代码如下:
#include <iostream>
#include <cstdio>
#include <cmath>
#define Y(x) 8.0*x*x*x*x+7.0*x*x*x+2.0*x*x+3.0*x+6.0-y
using namespace std;
double err=1e-10;
int main(){
int t;
scanf("%d",&t);
while(t--){
double y,mid=0.0;
scanf("%lf",&y);
double l=0,r=100;
if(Y(l)<=0&&Y(r)>=0){
while(r-l>err){
mid=(l+r)/2.0;
if(Y(mid)>err){
r=mid-err;
}
else{
l=mid+err;
}
}
printf("%.4f\n",mid);
}
else printf("No solution!\n");
}
}
/*
2
100
-4
*/