题目: 给一个n。构建一个2n*2n的方格。里面放一个半径为n的圆。求落在边上的和完全在内部的格子个数
注意:输出的时候。几组数之间有空行。最后一组后面没有
只需要算1/4的。由于对称性
#include <cstdio>
#include <string.h>
#include <cstdlib>
#include <cmath>
#include <ctgmath>
#include <iostream>
#include <vector>
#include <algorithm>
#include <map>
using namespace std;
//(0,0)到(m,n)距离的平方
int func(int m,int n){
return m*m+n*n;
}
int main()
{
//只需要考虑四分之一的区域
int n;
int count = 0;//计数,方便回车输出
while (cin>>n) {
int i,j;
double r = (n - 0.5) * (n - 0.5);//半径的平方
// cout<<r<<endl;
int neibu = 0;//内部
int bianjie = 0;//边上
//遍历所有格子的左下角
for(i=0; i<=n-1; i++){
for(j=0; j<=n-1; j++){
//左下和右上都在r内部
if( (func(i, j) < r) && (func(i+1, j+1) < r) ) neibu++;
else if( (func(i, j) < r) && (func(i+1, j+1) > r)) bianjie++;
}
}
// cout<<neibu<<endl<<bianjie;
if(count++) cout<<endl;
printf("In the case n = %d, %d cells contain segments of the circle.\n",n,bianjie*4);
printf("There are %d cells completely contained in the circle.\n",neibu*4);
}
return 0;
}
本文介绍了一种算法,用于计算一个2n*2n网格中,半径为n的圆内部及其边界上的格点数量。该算法通过遍历四分之一区域内的每个格子并利用对称性来简化计算过程。
402

被折叠的 条评论
为什么被折叠?



