Posted on 2012-08-14 21:39
hoshelly 閱讀(319)
評(píng)論(0) 編輯 收藏 引用 所屬分類(lèi):
Programming 、
DS && Algorithm
編寫(xiě)程序,對(duì)于N個(gè)隨機(jī)產(chǎn)生的單位正方形中的點(diǎn),統(tǒng)計(jì)可以被長(zhǎng)度小于d的直線連結(jié)的點(diǎn)對(duì)數(shù)。
程序如下:
typedef
struct{
float x;
float y; } point;
//定義點(diǎn)的數(shù)據(jù)類(lèi)型
float distance(point,point);
//兩點(diǎn)之間距離函數(shù)
float distance(point a,point b)
{
float dx= a.x - b.x, dy= a.y - b.y;
return sqrt(dx*dx + dy*dy);
}
//以上為頭文件 Point.h 的內(nèi)容
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include "Point.h"
float randFloat()
{
return 1.0*rand()/RAND_MAX; }
//產(chǎn)生隨機(jī)數(shù)的函數(shù)
int main()
{
float d,N;
int i,j,cnt=0;
scanf("%f%f",&d,&N);
//d為要求兩點(diǎn)之間距離小于的長(zhǎng)度,N為測(cè)試的點(diǎn)
point *a = (point *)malloc(
sizeof(point)*N);
//動(dòng)態(tài)生成數(shù)據(jù)類(lèi)型為point的數(shù)組a
for(i=0;i<N;i++)
{
a[i].x = randFloat(); a[i].y = randFloat();
}
for(i=0;i<N;i++)
for(j=i+1;j<N;j++)
if(distance(a[i],a[j])<d)
//如果兩點(diǎn)之間的距離小于d,那么cnt加1
cnt++;
printf("%d edges shorter than %f\n",cnt,d);
//輸出有多少條邊的長(zhǎng)度小于d
return 0;
}