From cbb74a8c010ef59c5bf3f043e3d25b3d260dd84f Mon Sep 17 00:00:00 2001 From: "Mr. Sam" Date: Wed, 15 Jul 2026 06:41:46 +0100 Subject: Go back to main.c --- Makefile | 4 ++-- main.c | 81 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 83 insertions(+), 2 deletions(-) create mode 100644 main.c diff --git a/Makefile b/Makefile index a578ad1..cfe7ae6 100755 --- a/Makefile +++ b/Makefile @@ -5,9 +5,9 @@ PREFIX = /usr/local CFLAGS = -std=c99 -pedantic -Wall -Wno-deprecated-declarations -Os -CC = gcc +CC = clang -SRC = stats.c +SRC = main.c all: ${CC} ${CFLAGS} ${SRC} -o stats diff --git a/main.c b/main.c new file mode 100644 index 0000000..81cdc33 --- /dev/null +++ b/main.c @@ -0,0 +1,81 @@ +#include +#include + +/* Enums make words into numbers, ergo no magic numbers */ +enum MODE { + MODE_MAX, + MODE_MIN, + MODE_DIFF +}; + +void help(void){ + printf("Usage: stats \n"); + exit(1); +} + +/* ADDING UP ALL THE VALUES */ +long sigma(int argc, char * argv[]) { + char *endptr; + long sum = 0; + + for (int i = 1; i < argc; i++) { + + sum += strtol(argv[i], &endptr, 10); /* convert the value to an integer and add it on */ + if (endptr == argv[i] || *endptr != '\0') { + help(); + } + + } + return sum; +} + +/* FINDING MEAN */ +float average(int n, int sum) { + float mean = (float) sum / n; + return mean; +} + +/* FINDING THE MIN/MAX/DIFFERENCE */ +long range(int argc, char * argv[], enum MODE mode) { + long low = strtol(argv[1], NULL, 10); + long high = low; + + for (int i = 1; i < argc; i++) { + long val = strtol(argv[i], NULL, 10); + if (val > high) high = val; + if (low > val) low = val; + } + + /* Check once and return what we need */ + switch (mode) { + case MODE_MAX: + return high; + case MODE_MIN: + return low; + case MODE_DIFF: + return high - low; + } + return 1; +} + +int main(int argc, char * argv[]) { + if (argc < 2) { /* Stop empty input */ + help(); + } + + long n = argc - 1; /* this is how many numbers there are */ + long sum = sigma(argc, argv); /* sigma means adding them all together */ + float mean = average(n, sum); /* the sum divided by the however many numbers there are */ + long min = range(argc, argv, MODE_MIN); /* Using enums here to use words instead of numbers */ + long max = range(argc, argv, MODE_MAX); + long diff = range(argc, argv, MODE_DIFF); + + + /* align text left for 6 and 12 right */ + printf("%-6s %12ld\n", "num:", n); + printf("%-6s %12ld\n", "sum:", sum); + printf("%-6s %12.3f\n", "mean:", mean); + printf("%-6s %12ld\n", "min:", min); + printf("%-6s %12ld\n", "max:", max); + printf("%-6s %12ld\n", "range:", diff); +} -- cgit v1.2.3