有4個圓塔,圓心分別為(2,2)、(-2,2)、(-2,-2)、(2,-2),圓半徑為1,見圖。這4個塔的高度為10m,塔以外無建築物。今輸入任一點的坐標,求該點的建築高度(塔外的高度為零)。
解題思路: 塔的半徑為1m,則x坐標小於-3或者大於3,以及y坐標大於3或者小於-3則都是0m的建築;其余則判斷輸入的坐標是否在各個圓塔的圓形范圍內。該點到各個圓心的距離是否大於1,小於則是10m建築,否則為0m建築。
math.h中提供了fabs(double)求一個浮點數的絕對值,輸入x,y坐標
fabs(fabs(x) - 2)得到輸入坐標距離圓心的橫軸距離;
fabs(fabs(y) - 2)得到舒服坐標距離圓心的縱軸距離;
三角形兩個直角邊長平方相加,然后開平方根得到第三邊長,若大於1,則不再圓塔范圍內。
答案:
#include <stdio.h>
#include <math.h>
void main()
{
int h;
double x, y, m, n, r;
printf("Please input a coordinate (x,y):");
scanf_s("%lf,%lf", &x, &y);
if (fabs(x) > 3 || fabs(y) > 3) {
h = 0;
printf("The height of the coordinate(%f,%f):h=%d\n", x, y, h);
return 0;
}
m = fabs(x) - 2; n = fabs(y) - 2;
r = sqrt(m * m + n * n);
if (r > 1)
h = 0;
else
h = 10;
printf("The height of the coordinate(%f,%f):h=%d\n", x, y, h);
system("pause");
return 0;
}