Skip to content

Instantly share code, notes, and snippets.

@hitode909
Forked from cocontusfine/pi.c
Created February 20, 2009 08:20
Show Gist options
  • Save hitode909/67373 to your computer and use it in GitHub Desktop.
Save hitode909/67373 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define MAX_NUM 999999999
typedef struct{
double ax;
double ay;
}position;
/* 任意の点の座標をランダムに取得 */
void get_position(position *pos){
pos->ax = rand()%101;
pos->ay = rand()%101;
}
/* 任意の点の座標を表示 */
void print_position(position pos){
printf("(%.1f,%.1f)\n", pos.ax, pos.ay);
}
/* 任意の二点間の距離を出す */
double dist_pos(position pos1, position pos2){
double diffx = pos1.ax - pos2.ax;
double diffy = pos1.ay - pos2.ay;
return sqrt(diffx * diffx + diffy * diffy);
}
/* 半径50の円の領域内に入っているのかどうかを判定 */
int circle_include_judge(position pos){
position cir = {50.0, 50.0};
return 50.0 >= dist_pos(cir, pos);
}
/* πを出す */
double cal_pi(double n1,double n2){
return ((double)4 * n1) / (n1 + n2);
}
/* main関数ですよ */
int main(void){
int i;
position point={};
double n1,n2;
n1=n2=0;
for(i=0;i<MAX_NUM;i++){
get_position(&point);
if( circle_include_judge(point)){
n1++;
}else{
n2++;
}
}
printf("%f\n",cal_pi(n1,n2));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment