Skip to content

Instantly share code, notes, and snippets.

@MarkyC
Created January 27, 2013 05:20
Show Gist options
  • Select an option

  • Save MarkyC/4646555 to your computer and use it in GitHub Desktop.

Select an option

Save MarkyC/4646555 to your computer and use it in GitHub Desktop.
/** avg.c
* Author: Marco Cirillo
* Uses getchar() to compute an average of a series of digits
*/
#include <stdio.h>
int main(int argc, char* argv[]) {
int total=0,subtotal=0,n=0;
int c;
printf("Enter numbers followed by spaces and press enter when finished: ");
while (c = getchar()) {
if (isdigit(c)) {
// The char is not a letter, add to running subtotal
subtotal *= 10;
subtotal += c - '0';
} else if (isspace(c)) {
// add the subtotal to the total, and increment count of given numbers
total += subtotal;
subtotal = 0;
n++;
if (c == '\n') break;
}
}
printf("Average: %.2f\n", (float) (total/n));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment