題目連結: https://zerojudge.tw/ShowProblem?problemid=c049
#
# 題目
在一個邊長為 2n 的正方形棋盤中央畫一個直徑為 2n-1 的圓,以下的圖為 n=3,
寫一個程式判斷有多少個格子是一部份在圓中,以及有多少個格子是完全被包含在圓當中。
# 思路
先去窮舉 1/4 圓的格子情形,再去乘 4
利用畢氏定理判斷格子的四個點是否都在圓內,或部分在園內
# 程式碼
#include<iostream> | |
#define AllinRange r1<=range&&r2<=range&&r3<=range&&r4<=range | |
#define PartinRange r1<=range||r2<=range||r3<=range||r4<=range | |
using namespace std; | |
int main(){ | |
int n; | |
while(cin>>n){ | |
int range = (2*n-1)*(2*n-1); | |
int count_part = 0,count_all = 0; | |
for(int i=0; i<n+1; i++){ | |
for(int j=0; j<n+1; j++){ | |
int r1, r2, r3, r4; // 左下 右下 左上 右上 | |
r1 = 4*(i*i + j*j); | |
r2 = 4*((i+1)*(i+1) + j*j); | |
r3 = 4*(i*i + (j+1)*(j+1)); | |
r4 = 4*((i+1)*(i+1) + (j+1)*(j+1)); | |
if(AllinRange) | |
count_all++; | |
else | |
if(PartinRange) | |
count_part++; | |
else | |
break; | |
} | |
} | |
cout<<"In the case n = "<<n<<", "<<count_part<<" cells contain segments of the circle.\nThere are "<<count_all<<" cells completely contained in the circle.\n"; | |
} | |
} |