www.pudn.com > CG2Programs.rar > pieChart.c
/* pieChart, Chapter 3, p. 138-139 */ #include#include #include "graphics.h" #define N_DATA 12 #define ROUND(a) ((int)(a+0.5)) typedef enum {Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec} Months; int readData (char * inFile, float * data) { int fileError = FALSE; FILE * fp; Months month; if ((fp = fopen (inFile, "r")) == NULL) fileError = TRUE; else { for (month = Jan; month <= Dec; month++) fscanf (fp, "%f", &data[month]); fclose (fp); } return (fileError); } /* EXAMPLE STARTS HERE */ #define TWO_PI 6.28 void pieChart (float * data) { wcPt2 pts[2], center; float radius = WINDOW_HEIGHT / 4.0; float newSlice, total = 0.0, lastSlice = 0.0; Months month; center.x = WINDOW_WIDTH / 2; center.y = WINDOW_HEIGHT / 2; pCircle (center, radius); for (month = Jan; month <= Dec; month++) total += data[month]; pts[0].x = center.x; pts[0].y = center.y; for (month = Jan; month <= Dec; month++) { newSlice = TWO_PI * data[month] / total + lastSlice; pts[1].x = center.x + radius * cosf (newSlice); pts[1].y = center.y + radius * sinf (newSlice); pPolyline (2, pts); lastSlice = newSlice; } } /* EXAMPLE ENDS HERE */ void main (int argc, char ** argv) { float data[N_DATA]; int dataError = FALSE; long windowID; if (argc < 2) { fprintf (stderr, "Usage: %s dataFileName\n", argv[0]); exit (); } dataError = readData (argv[1], data); if (dataError) { fprintf (stderr, "%s error. Couldn't read data file %s\n", argv[1]); exit (); } windowID = openGraphics (*argv, WINDOW_WIDTH, WINDOW_HEIGHT); setBackground (WHITE); setColor (BLACK); pieChart (data); sleep (10); closeGraphics (windowID); }