Q356:Square Pegs And Round Holes
在一個邊長為 2n 的正方形棋盤中央畫一個直徑為 2n-1 的圓,以下的圖為n=3
Input
輸入包含好幾組測試資料,每組一列,含有一個正整數 n(n<=150)
Output
對每一組測試資料,輸出2列,第一列為部分被包含在圓中的格子數。第二列為完全被包含在圓中的格子數。
請注意:各測試資料之間要空一列。請參考Sample output
Sample Iutput
3
4
4
Sample Output
In the case n = 3, 20 cells contain segments of the circle.
There are 12 cells completely contained in the circle.
In the case n = 4, 28 cells contain segments of the circle.
There are 24 cells completely contained in the circle.
There are 12 cells completely contained in the circle.
In the case n = 4, 28 cells contain segments of the circle.
There are 24 cells completely contained in the circle.
import java.util.Scanner;
public class UVA_356 {
static int n;
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
while((n=sc.nextInt())<=150){
System.out.println();
int cover=0;
int cross=0;
for(int i=0;i<=n*2;i++){
for(int j=0;j<=n*2;j++){ //上下左右四個點 (0,0)(0,1)(1,0)(0.0)
if(dist(i,j)<=n-0.5 && dist(i,j+1)<=n-0.5 && dist(i+1,j)<=n-0.5
&& dist(i+1,j+1)<=n-0.5)
cover++;
else if(dist(i,j)<=n-0.5 || dist(i,j+1)<=n-0.5 || dist(i+1,j)<=n-0.5
|| dist(i+1,j+1)<=n-0.5)
cross++;
}
}
System.out.printf("In the case n = %d, %d cells contain segments of the circle.\n",n,cross);
System.out.printf("There are %d cells completely contained in the circle.\n",cover);
}
}
private static double dist(int i,int j){
return Math.sqrt((n-i)*(n-i)+(n-j)*(n-j));
}
}
沒有留言:
張貼留言