Update du3/program.c

This commit is contained in:
Denis Landa 2025-10-16 17:07:29 +00:00
parent a9c8b2bc84
commit 9770be8838

View File

@ -9,35 +9,36 @@ struct listok {
float cena; float cena;
}; };
void add_listok(struct listok *p, int *n){ int add_listok(struct listok *p, int *n) {
if (fgets(p[*n].nazov, 101, stdin) == NULL){ if (fgets(p[*n].nazov, 101, stdin) == NULL) {
exit(0); return 0;
} }
p[*n].nazov[strcspn(p[*n].nazov, "\n")] = 0; p[*n].nazov[strcspn(p[*n].nazov, "\n")] = 0;
if (scanf("%f", &p[*n].cena) != 1){ if (scanf("%f", &p[*n].cena) != 1) {
exit(0); return 0;
} }
getchar(); getchar();
*n = *n + 1; *n = *n + 1;
return 1;
} }
int compare(struct listok *a, struct listok *b){ int compare(struct listok *a, struct listok *b) {
if (a->cena > b->cena){ if (a->cena > b->cena) {
return 1; return 1;
} }
if (a->cena < b->cena){ if (a->cena < b->cena) {
return -1; return -1;
} }
return strcmp(a->nazov, b->nazov); return strcmp(a->nazov, b->nazov);
} }
void sort_listok(struct listok *p, int n){ void sort_listok(struct listok *p, int n) {
for (int i = 0; i < n - 1; i++){ for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++){ for (int j = i + 1; j < n; j++) {
if (compare(&p[i], &p[j]) > 0){ if (compare(&p[i], &p[j]) > 0) {
struct listok tmp = p[i]; struct listok tmp = p[i];
p[i] = p[j]; p[i] = p[j];
p[j] = tmp; p[j] = tmp;
@ -46,19 +47,18 @@ void sort_listok(struct listok *p, int n){
} }
} }
void print_listok(struct listok *p, int n){ void print_listok(struct listok *p, int n) {
for (int i = 0; i < n; i++){ for (int i = 0; i < n; i++) {
printf("%s\n", p[i].nazov); printf("%s\n", p[i].nazov);
printf("%f\n", p[i].cena); printf("%f\n", p[i].cena);
} }
} }
int main(){ int main() {
struct listok p[LIST_SIZE]; struct listok p[LIST_SIZE];
int n = 0; int n = 0;
while (1){ while (add_listok(p, &n)) {
add_listok(p, &n);
} }
sort_listok(p, n); sort_listok(p, n);