descending.csv and ascendiny.uS 3. (5 points) In this problem, we defined a stru
ID: 3701022 • Letter: D
Question
descending.csv and ascendiny.uS 3. (5 points) In this problem, we defined a structure that can be used to represent information for hurricanes: Struct hurricane char name[20]; int year, category; Next two problems refer to the file storms2.txt, which contains information for the strongest hurricanes in the United States during 1950 to 2002. Note that the information in the file is ordered by year. Write a program to read the information in storms2.txt. Use the preceding stru print a report with the average category of these hurricanes. Use an output format similar to the following; Hurricane Summary for Strongest Hurricanes in 1950- 2002 Average Category: xx.x Note: You do not need an array to solve this problem.Explanation / Answer
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Hurricane structure to read records
struct hurricane
{
char name[20];
int year, category;
};
int main ()
{
FILE *infile;
struct hurricane record;
int count = 0, catsum = 0; // for category sum
float avgcat = 0; // for average category
infile = fopen ("storms2.txt", "r");
if (infile == NULL)
{
fprintf(stderr, " Error opening file ");
exit (1);
}
// reading file contents to structure till the end of file
while(fread(&record, sizeof(struct hurricane), 1, infile)) {
count ++;
catsum = catsum + record.category; // adding up all category values
}
avgcat = (float) catsum / count ; //calculating average category using floating point operations
printf(" Hurricane Summary for Strongest Hurricanes in 1950-2002");
printf(" Average Category: %.1f", avgcat); // %.1f for 1 decimal point after . i.e., xx.x
fclose(infile);
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.