Add solution for problem 3

This commit is contained in:
Myles Busig 2024-10-30 00:34:59 -07:00
parent 6cdb4014d0
commit f01e0b9e31
4 changed files with 65 additions and 0 deletions

7
include/p3.h Normal file
View File

@ -0,0 +1,7 @@
#ifndef P3_H
#define P3_H
double sum_file(const char* filename);
#endif

4
input_p3.dat Normal file
View File

@ -0,0 +1,4 @@
1.0
2.2
3.0
5.4

View File

@ -2,6 +2,7 @@
#include "p1.h"
#include "p2.h"
#include "p3.h"
int main(void) {
// Problem 1
@ -21,6 +22,11 @@ int main(void) {
printf("Average: %.2lf, Min: %.2lf, Max: %.2lf\n", avg, min, max);
// Problem 3
double sum_of_file = sum_file("input_p3.dat");
printf("Sum of file: %.2lf\n", sum_of_file);
return 0;
}

48
src/p3.c Normal file
View File

@ -0,0 +1,48 @@
#include "p3.h"
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
double sum_file(const char* filename) {
FILE* infile = fopen(filename, "r");
double sum = 0.0;
double value = 0.0;
// NOTE: Using feof may fail if you're not careful! For example, if the file
// being read from contains trailing whitespace characters, EOF may not
// be set until one additional read is performed. In this case, this would
// cause fscanf to attempt to read one additional value that does not exist.
// On Linux, this additional read is needed even if there is no trailing
// whitespace, although this may differ on other systems.
//
// As another example, if fscanf encounters an unexpected value, the position
// inside of the file will not be increased. Since we are attempting to read
// floating-point numbers, if we add an alphabetic character to the input file,
// fscanf will be stuck in an infinite loop trying to read invalid data and
// never progressing.
/*while (!feof(infile)) {
value = 0.0;
fscanf(infile, "%lf", &value);
// Try changing the input file and see what this prints!
printf("(feof) Adding value %.2lf to sum\n", value);
sum += value;
}*/
// A more reliable way of repeatedly reading from a file is checking
// the return value of fscanf. On success, fscanf will return the number
// of values read.
while (fscanf(infile, "%lf", &value) == 1) {
printf("(fscanf) Adding value %.2lf to sum\n", value);
sum += value;
}
fclose(infile);
return sum;
}