Last active
December 26, 2015 06:49
-
-
Save chihuahua/7110049 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * Determine the mean of a list of integers in a file 'nums.txt'. | |
| * One integer is on each line in the file. Writes the mean in a | |
| * nicely formatted way into a file mean.txt. Will override | |
| * mean.txt if it exists already. | |
| * @author Chi Zeng ([email protected]) + section-mates. | |
| * Oct. 22, 2013 | |
| */ | |
| #include <stdio.h> | |
| #include <stdlib.h> | |
| int main() | |
| { | |
| FILE* sourceFile = fopen("nums.txt", "r"); | |
| if (!sourceFile) | |
| { | |
| // ensure source file exists. | |
| printf("The source file does not exist.\n"); | |
| return 1; | |
| } | |
| // read no more than this many bytes per line. | |
| int maxBytes = 31; | |
| char buffer[maxBytes]; | |
| int sum = 0; | |
| int numElements = 0; | |
| while (fgets(buffer, maxBytes, sourceFile)) | |
| { | |
| // add up the numbers. | |
| sum += atoi(buffer); | |
| numElements += 1; | |
| } | |
| // compute the mean. | |
| double mean = sum / (double) numElements; | |
| // write result to a new file mean.txt. | |
| // if mean.txt exists, it will be overriden. | |
| FILE* destFile = fopen("mean.txt", "w"); | |
| fprintf(destFile, "The mean is %.2f\n", mean); | |
| // close our files. | |
| fclose(sourceFile); | |
| fclose(destFile); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment