Expanding Rods(二分法)
Expanding Rods
When a thin rod of length L is heated n degrees, it expands to a new length L’=(1+n*C)*L, where C is the coefficient of heat expansion.
When a thin rod is mounted on two solid walls and then heated, it expands and takes the shape of a circular segment, the original rod being the chord of the segment.
Your task is to compute the distance by which the center of the rod is displaced.
Input
The input contains multiple lines. Each line of input contains three non-negative numbers: the initial lenth of the rod in millimeters, the temperature change in degrees and the coefficient of heat expansion of the material. Input data guarantee that no rod expands by more than one half of its original length. The last line of input contains three negative numbers and it should not be processed.
Output
For each line of input, output one line with the displacement of the center of the rod in millimeters with 3 digits of precision.
Sample Input
1000 100 0.0001
15000 10 0.00006
10 0 0.001
-1 -1 -1
Sample Output
61.329
225.020
0.000
思路:
二分法。看了大佬的思路受益匪浅,找到数学关系然后就可以了。
完整代码:
#include<iostream>
#include<cstdio>
#include<cmath>
using namespace std;
const double eps=1e-5;
double L,n,C; //杆长,温度,热力系数
void binary()
{
double bet; //延伸后杆中心到之前杆中心的距离
double l=0.0,r=0.5*L; //上下界,上界取0.5*L是因为方便而不是最小上界就是这个数
double L1=(1+n*C)*L; //变之后的杆长
while(r-l>eps) //因为定义的都是double型用r>l会死循环,所以加入精度
{
bet=(l+r)/2;
double R=(4*bet*bet+L*L)/(8*bet); //圆的半径
if(2*R*asin(L/(2*R))<L1)
{
l=bet;
}
else
{
r=bet;
}
}
printf("%.3lf\n",bet);
}
int main()
{
while(cin>>L>>n>>C)
{
if(L<0&&n<0&&C<0)
{
break;
}
binary();
}
return 0;
}
注意:用 C++ 提交,我用 G++WA了好多好多发一直都不知道为什么,后来用 C++ 提交就过了。
上一篇: 裸睡的好处有哪些?男人裸睡大有益处
下一篇: 上海某公司android面试题