So I\'m pretty new to C programming and having a lot of trouble getting this to
ID: 3922099 • Letter: S
Question
So I'm pretty new to C programming and having a lot of trouble getting this to work. I need to read in a file that has data on it (couple lines in sets of 2's) and I need to use that data to print out the perimeter and area of a polygon within a circle. My professor didn't really do a good job of setting us up so I'm having trouble debugging my work. This is what I have wrote so far.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define INPUT_FILE "lab3.dat"
#define ANSWER_FILE "lab3.txt"
int main(void)
{
double nsides;
double radius;
double perimeter;
double area;
FILE* my_data;
FILE* out_file;
my_data = fopen(INPUT_FILE, "r");
if(my_data == NULL)
{
printf("Error on opening the data file ");
}
out_file = fopen(ANSWER_FILE,"w")
if(out_file == NULL)
{
printf("Error on opening the output file ");
}
perimeter = 2*nsides*radius*sin(M_PI/nsides);
area = 0.5*nsides*(radius*radius)*sin((2*M_PI)/nsides);
fprintf(ANSWER_FILE, " Nima Sarrafzadeh. Lab 3. ");
fprintf(ANSWER_FILE, " Number Perimeter Area Of ");
fprintf(ANSWER_FILE, " Radius Of Sides Of Polygon Polygon ");
fprintf(ANSWER_FILE, "-------- -------- ------------ ----------- ");
while((fscanf(my_data, "%d%f", &radius, &nsides))==2)
{
fprintf(ANSWER_FILE, ("%d", radius), " ", ("%d", nsides), " ", ("%d", perimeter), " ", ("%d", area);
}
fclose(INPUT_FILE);
fclose(ANSWER_FILE);
}
Explanation / Answer
Hi, I have fixed all the issue.
Please find my code.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define INPUT_FILE "lab3.dat"
#define ANSWER_FILE "lab3.txt"
int main(void)
{
int nsides;
double radius;
double perimeter;
double area;
FILE* my_data;
FILE* out_file;
my_data = fopen(INPUT_FILE, "r");
if(my_data == NULL)
{
printf("Error on opening the data file ");
exit(0);
}
out_file = fopen(ANSWER_FILE,"w");
if(out_file == NULL)
{
printf("Error on opening the output file ");
exit(0);
}
// now reading number of sides and radius value from file
if((fscanf(my_data, "%d%lf", &nsides, &radius))!=2)
{
printf("Data is not available in file ");
exit(0);
}
perimeter = 2*nsides*radius*sin(M_PI/nsides);
area = 0.5*nsides*(radius*radius)*sin((2*M_PI)/nsides);
fprintf(out_file, " Nima Sarrafzadeh. Lab 3. ");
fprintf(out_file, " Number Perimeter Area Of ");
fprintf(out_file, " Radius Of Sides Of Polygon Polygon ");
fprintf(out_file, "-------- -------- ------------ ----------- ");
fprintf(out_file, "%d %lf %lf %lf",nsides, radius, perimeter, area);
fclose(my_data);
fclose(out_file);
}
######## lab3.dat ########
5
4.5
######## output: lab3.txt ##############
Nima Sarrafzadeh. Lab 3.
Number Perimeter Area Of
Radius Of Sides Of Polygon Polygon
-------- -------- ------------ -----------
5 4.500000 26.450336 48.147236
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.