Statistika temperature
Napisati program koji kroz argumente komandne linije dobija listu celobrojnih temperatura i ispisuje traženu statistiku nad njima: maksimalnu (max), minimalnu (min) ili prosečnu (avg) temperaturu.
Ulaz
Program se pokreće komandnom linijom oblika
./tempstat <op> <t1> <t2> ... <tN>
gde je <op> jedna od vrednosti max, min ili avg, a <ti> su celobrojne temperature.
Izlaz
Na standardni izlaz ispisati traženu maksimalnu ili minimalnu temperaturu kao ceo broj, odnosno prosečnu temperaturu sa tačno dve decimale.
U slučaju greške, na standardni izlaz za greške ispisati odgovarajuću poruku i završiti program sa statusom neuspeha (1).
Primer
command line
./tempstat max 12 -5 20 7
stdout
20
Primer
command line
./tempstat min 12 -5
stdout
-5
Primer
command line
./tempstat avg -5 5 0 5
stdout
1.25
Primer
command line
./tempstat max
stderr
Error: Not enough arguments.
Primer
command line
./tempstat mid 10 0
stderr
Error: Unknown option mid.
Rešenje
tempstat.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
if (argc < 3) {
fprintf(stderr, "Error: Not enough arguments.\n");
exit(EXIT_FAILURE);
}
if (strcmp(argv[1], "max") == 0) {
int max_temp = atoi(argv[2]);
for (int i = 3; i < argc; i++) {
int temp = atoi(argv[i]);
if (temp > max_temp) {
max_temp = temp;
}
}
printf("%d\n", max_temp);
} else if (strcmp(argv[1], "min") == 0) {
int min_temp = atoi(argv[2]);
for (int i = 3; i < argc; i++) {
int temp = atoi(argv[i]);
if (temp < min_temp) {
min_temp = temp;
}
}
printf("%d\n", min_temp);
} else if (strcmp(argv[1], "avg") == 0) {
int sum = 0;
int count = argc - 2;
for (int i = 2; i < argc; i++) {
sum += atoi(argv[i]);
}
printf("%.2f\n", (float)sum / count);
} else {
fprintf(stderr, "Error: Unknown option %s.\n", argv[1]);
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}