题目:不难理解。见题目本身。
分析:
方法一:自己想了很久,用纯数学方法做的,还是没有计算机点思维。见草稿。在1/4圆内,算圆弧与坐标轴x=k(n-1>=k>=1)的交点的高h。h取整 就是红色长方形(点右侧)内的方格数,全加起来就是完全在圆内的方格数。而蓝色则是x向上取整后(点左侧),所包括的所有所求的方格 - n(内+碰,少了n个格子)。
方法二:判断1/4圆,每个方格对角线的格点A、B,分别到原点O的距离。
|AO| < R, |BO| < R说明方格在圆内。
|AO| > R, |BO| < R说明方格被碰到。
|AO| > R, |BO| > R 说明方格在圆外。
注意:1.输出时,有个诡异的地方,我反复看题目也不能明白ac的格式与题目所说的格式是一致的(老外的表达思维没能理解)。见代码
方法一
#include"stdlib.h"
#include"stdio.h"
#include"string.h"
#include"math.h"
int main()
{
int n,k,a_quarter_segments,a_quarter_whole,a_quarter_touchandcontain,flag=0;
double h[150],h2;
while(scanf("%d",&n)==1)
{
a_quarter_whole=0;
a_quarter_segments=0;
a_quarter_touchandcontain=0;
for(k=1; k<n; k++)
{
h2=(2*k-1)*n-k*k+0.25;
h[k]=sqrt(h2);
}
for(k=1; k<n; k++)
{
a_quarter_whole+=(int)h[k];
if((h[k]-(int)h[k])<1e-7)
{
a_quarter_touchandcontain+=(int)h[k];
}
else
a_quarter_touchandcontain+=(int)h[k]+1;
}
a_quarter_segments=a_quarter_touchandcontain+n-a_quarter_whole;
if(flag!=0) printf("\n");
printf("In the case n = %d, %d cells contain segments of the circle.\n",n,4*a_quarter_segments);
printf("There are %d cells completely contained in the circle.\n",4*a_quarter_whole);
flag++;
}
return 0;
}
方法二1
#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;
}
此代码来源 优快云博主Harder_LZA
https://blog.youkuaiyun.com/surpasslll/article/details/69247606 ↩︎