UVA13045 Drawing Polygon
题目描述
Link: https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=866&page=show_problem&problem=4943
输入格式
输出格式
输入输出样例 #1
输入 #1
2 4 5 0 0 5 5 0 0输出 #1
Case #1: 0.000000 0.000000 5.000000 0.000000 5.000000 5.000000 0.000000 5.000000 Case #2: 0.000000 0.000000 5.000000 0.000000 6.545085 4.755283 2.500000 7.694209 -1.545085 4.755283Solution
题目说明
已知一个正n nn边形的边长l ll,以及这个多边形左下角顶点的坐标( x , y ) (x,y)(x,y),求这个多边形每个顶点的坐标。
分析
本题属于典型的模拟,从题目描述看,这个过程和 Python 的 turtle 非常类似。
一个正n nn边形的性质包括:
- 外角和是2 π 2\pi2π,每个外角(也就是绘制相邻两条边时需要转过的角度)皆为2 π n \dfrac{2\pi}{n}n2π;
- 所有的边长相等。
基于上述两点,绘制多边形时(也就是模拟一只 turtle),自始至终不断更新当前的朝向(角度θ \thetaθ)以及坐标位置( x , y ) (x,y)(x,y)。当边长为l ll,方向的角度为θ \thetaθ时,绘制这条边时…
- x xx的值增加l cos θ l\cos\thetalcosθ;
- y yy的值增加l sin θ l\sin\thetalsinθ;
得到的值即为下一个顶点的坐标。到达下一个顶点后,θ \thetaθ角度增加2 π n \dfrac{2\pi}{n}n2π,重复这一过程直到绘制完全部顶点即可。由于第一条边和x xx轴平行,因此θ \thetaθ角度初始化为零。
需要说明的是:
- 相邻两组数据之间要输出一个空行(这一点在 PDF 题面没有体现);
- 浮点数有正负0 00之分,不能输出
-0.000000; - Case 的字母 c 要大写。
完整代码
#include<iostream>#include<cmath>usingnamespacestd;constlongdoublepi=3.1415926535897932385l;//(x,y)是起点坐标, n是多边形的边数, l是多边形的边长, t是数据组数longdoublen,l,x,y;intt;voidsolve(){staticintk=1;cin>>n>>l>>x>>y;printf("Case #%d:\n",k);longdoublerotationAngle=2.0*pi/n;longdoubledirection=0;for(inti=1;i<=n;i+=1){if(fabsl(x)<=1e-9)x=0.;if(fabsl(y)<=1e-9)y=0.;printf("%.6Lf %.6Lf\n",x,y);x+=l*cosl(direction);y+=l*sinl(direction);direction+=rotationAngle;}cout<<endl;k+=1;}intmain(){cin>>t;for(inti=1;i<=t;i+=1)solve();}