/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 4 -*- */
/*
* main.c
* Copyright (C) DMGualtieri 2018
*
* triangle_median is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* triangle_median is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see .
*/
/*
For triangles made from a stick randomly broken into three pieces,
find the median and mean areas.
*/
// Note - Written more for readability than speed!
#include
#include
#include
#include
#define trials 100000
#define iterations 1000
long int i,j,k, triangles;
int t_flag;
float point1,point2,side1,side2,side3,s,A,sum,tmp;
float area[trials]; //note - only about a quarter of the elements are really needed
FILE *outdata;
//generates a psuedo-random float between 0.0 and 0.999...
float randfloat()
{
return (((float)rand()/RAND_MAX));
}
int main()
{
//Seed random number generator
srand ( (unsigned)time ( NULL ) );
//Open output datafile
if ((outdata = fopen("triangle_data.txt","w"))==NULL)
{printf ("\nOutput file cannot be opened.\n");
exit (1);}
else
{
printf("Output file = triangle_data.txt");
}
printf("\ntrials = %d\titerations = %d\n",trials,iterations);
for(k=0;k (side2+side3)) t_flag = 0;
if (side2> (side1+side3)) t_flag = 0;
if (side3> (side1+side2)) t_flag = 0;
if (t_flag ==1)
{
//do area calculation with Heron's formula
s = (side1 + side2 + side3)/2;
A = sqrt(s*(s-side1)*(s-side2)*(s-side3));
area[triangles]=A;
sum = sum + A;
triangles++;
}
}
//sort array in ascending order - needed to get the median value
for (i = 0; i < triangles; i++)
{
for (j = 0; j < triangles; j++)
{
if (area[j] > area[i])
{
tmp = area[i];
area[i] = area[j];
area[j] = tmp;
}
}
}
//print sorted array
//for (int i = 0; i < triangles; i++)
//{
//printf("%f\t", area[i]);
//}
printf("Average area = %lf\tMedian area = %f\n",sum/triangles,area[(int)(triangles/2)]);
fprintf(outdata, "%lf\t%f\n",sum/triangles,area[(int)(triangles/2)]);
}
//Close output file
fclose(outdata);
return (0);
}