Created
September 11, 2012 22:38
-
-
Save only-entertainment/3702682 to your computer and use it in GitHub Desktop.
Take the average and display it with a custom display function
This file contains 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
#include <stdio.h> | |
// Define functions | |
void display_average(float); | |
int main(int argc, char * argv[]) { | |
float accumulator = 0.0; | |
int num_of_times = 0; | |
int ii = 1; | |
float average = 0.0; | |
// Ask until we have a valid input | |
while (1) { | |
// Get the user input | |
printf("How many?: "); | |
scanf("%d", &num_of_times); | |
printf("\n"); | |
// If number of times to run is less than 0, | |
// tell them, and try again | |
if (num_of_times <= 0) { | |
printf("Please enter a number greater than 0.\n\n"); | |
} else{ | |
// We have a valid number now, break out of this loop | |
break; | |
} | |
} | |
// Now that we have the number of times to ask | |
// the user for a number, do it | |
for (ii = 0; ii < num_of_times; ii++) { | |
float user_input = 0.0; | |
// Get the user input to add to | |
// the accumulator | |
printf("User Number: "); | |
scanf("%f", &user_input); | |
// Add the input | |
accumulator += user_input; | |
} | |
// Get the average | |
average = accumulator / (float)num_of_times; | |
// Display it to the user | |
display_average(average); | |
return 0; | |
} | |
void display_average(float average) { | |
printf("\nAverage = %f\n", average); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment