Reputation: 1
I am writing a program for class that has to use functions and I am not getting any syntax errors and have tried multiple times to change things with no success. The function is not saving into the .out file correctly.
Here is the code:
/* LAB13, functions */
/* Given the number of sides of an n-side regular polygon */
/* and the radius of the circle, find the perimeter and */
/* area of the polygon */
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define IN_FILE "lab13.dat"
#define OUT_FILE "lab13.out"
/* function prototypes */
double get_perimeter(double n, double radius);
double get_area(double n, double radius);
int main(void)
{
double n; /* number of sides */
double radius; /* radius of the circle */
double area; /* area of the polygon */
double perimeter; /* perimeter of the polygon */
FILE * data_in; /* input file pointer */
FILE * data_out; /* output file pointer */
/* Open the two required files */
data_in = fopen(IN_FILE, "r");
if (data_in == NULL)
{
printf("Error on fopen file %s \n", IN_FILE);
exit(EXIT_FAILURE);
}
data_out = fopen(OUT_FILE, "w");
if (data_out == NULL)
{
printf("Error on fopen file %s \n", OUT_FILE);
exit(EXIT_FAILURE);
}
/* Print headers */
fprintf(data_out, "\nScott _________. Lab13. \n\n");
fprintf(data_out, " Number Of Sides Radius Perimeter Area \n");
fprintf(data_out, " of Polygon of Circle of Polygon of Circle \n");
fprintf(data_out, "---------------- --------- ---------- --------- \n");
while ((fscanf(data_in, "%lf%lf", &n, &radius))== 2)
{
perimeter = get_perimeter(n, radius);
area = get_area(n, radius);
fprintf(data_out,"%8i %17.3f %11.3f %10.3f\n",
n, radius, perimeter, area);
}
printf("\n");
fclose(data_in);
fclose(data_out);
return EXIT_SUCCESS;
}
/*-----------------------------------------------------------*/
double get_perimeter(double n, double radius)
{
double perimeter;
perimeter = 2 * n * radius * (sin(M_PI/n));
return perimeter;
}
/*-----------------------------------------------------------*/
double get_area(double n, double radius)
{
double area;
area = 0.5 * n * (radius*radius) * (sin(2*M_PI)/n);
return area;
}
/*-----------------------------------------------------------*/
The lab13.dat file that it is grabbing from is:
3.0 16.5
5.0 9.1
7.0 11.5
The output from running the program
Upvotes: 0
Views: 99
Reputation: 74
You're problem is in the fprintf.
fprintf(data_out,"%8i %17.3f %11.3f %10.3f\n", n, radius, perimeter, area);
i is not the format specifier you want, use f. Probably a typo
Upvotes: 1
Reputation: 239732
You're printing n
, which is a double
, using the format %8i
, which expects an int
. If you want to print a double
but suppress any possible non-integer part, use a precision of 0, as in %8.0f
.
Upvotes: 1