题目描述:
求杆子受热膨胀后中心高度的变化。
题型类别:
二分法解决几何问题。
源代码:
#include<iostream>
#include<math.h>
#include<stdio.h>
#include<iomanip>
using namespace std;
#define esp 1e-5
int main()
{
double L,n,c;
double r,h,s; //半径r,要求的高度h,弧长s
double low,high,mid;
while(scanf("%lf%lf%lf",&L,&n,&c)!=EOF)
{
if(L<0 && n<0 && c<0)
break;
s=(1+n*c)*L;
low=0.0;
high=0.5*L; //如果换成是high=L/2就不对了,精度问题
while((high-low)>esp)
{
mid=(low+high)/2;
r=(L*L+4*mid*mid)/(8*mid);
if(2*r*asin(L/(2*r))<s)
low=mid;
else
high=mid;
}
h=mid;
cout<<fixed<<setprecision(3)<<h<<endl; //小数点有效位数为3
//printf("%.3lf\n",h); 换成是这句话就不对了
}
return 0;
}
题目中有很多细节的地方需要注意,第一,关于 0.5*L 与 L/2 的区别,精度不一致;第二,小数点有效位数的表示,用printf () 就不对了。。。。嗯,这是为什么呢?