当前位置: 代码迷 >> 综合 >> hdu 2289 Cup 【二分】
  详细解决方案

hdu 2289 Cup 【二分】

热度:28   发布时间:2023-12-16 06:06:50.0

题目

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.

输入

The input consists of several test cases. The first line of input contains an integer T T 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 , r, R, H, V, r,R,H,V, representing the bottom radius, the top radius, the height and the volume of the hot water.
Technical Specification

  1. T ≤ 20. T ≤ 20. T20.
  2. 1 ≤ r , R , H ≤ 100 ; 0 ≤ V ≤ 1000 , 000 , 000. 1 ≤ r, R, H ≤ 100; 0 ≤ V ≤ 1000,000,000. 1r,R,H100;0V1000,000,000.
  3. r ≤ R . r ≤ R. rR.
  4. r, R, H, V are separated by ONE whitespace.
  5. There is NO empty line between two neighboring cases.

输出

For each test case, output the height of hot water on a single line. Please round it to six fractional digits.

样例输入

1
100 100 100 3141562

样例输出

99.999024

题目分析

本题通过确定圆台形杯子的下底半径 r r r,上底半径 R R R,杯高 H H H,以及杯中水的体积 V V V,以此来确定杯中水的高度。此题难点在于确定精度。而我们可以通过二分的方法来将假设的高度不断趋近于杯中水的高度,即通过我们假设一个高度,由此通过圆台体积公式 V = 1 3 π h ( R 2 + R r + r 2 ) V=\frac 1 3 \pi h(R^2+Rr+r^2) V=31?πh(R2+Rr+r2)解出此时的体积,并与水的体积进行比较,确定最终的高度。

代码

#include<iostream>
#include<cstdio>
#include<math.h>
using namespace std;const double pi = acos(-1.0);//圆周率的值,直接影响结果精度
const double INF= 1e-9;//设置的差值精度
//计算假定高度的体积
double height(double r,double R,double H,double V)
{
    double h,R1,V1;double start=0.0f,end=H;while(fabs(end-start)>INF){
    h = start+(end-start)/2;//二分假定高度R1= (h/H)*(R-r)+r;//计算假定高度的上底半径V1= pi*h*(R1*R1+R1*r+r*r)/3.0f;//计算假定高度的体积if(fabs(V1-V)<=INF)return h;else if(V1>V)end = h-INF;elsestart = h+INF;}return h;
}int main()
{
    int T;cin >> T;double h,r,R,H,V;while(T--){
    scanf("%lf%lf%lf%lf",&r,&R,&H,&V);h = height(r,R,H,V);printf("%.6f\n",h);//输出小数点后6位}return 0;
}

运行结果

在这里插入图片描述

题目链接

http://acm.hdu.edu.cn/showproblem.php?pid=2289