C언어 알고리즘입니다.
글쓴이: studyhelpmeplz / 작성시간: 화, 2021/09/21 - 5:57오후
키로 검색하려고 수정을 하는데요 여기서 어떻게 해야할지 모르겠습니다.
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct { char name[10]; int height; int weight; }Person; int npcmp(const Person *x, const Person *y) { if (x->height == y->height) return 0; else return -1; } int main(void) { Person x[] = { { "김영준", 179, 79 }, { "박현규", 172, 63 }, { "이수진", 176, 52 }, { "최윤미", 165, 51 }, { "함진아", 181, 73 }, { "홍연의", 172, 84 } }; int nx = sizeof(x) / sizeof(x[0]); int retry; puts("키로 검색합니다"); do { Person temp, *p; printf("키 : "); scanf("%d", temp.name); p = bsearch(&temp, x, nx, sizeof(Person), (int(*)(const void*, const void*))npcmp); if (p == NULL) puts("검색에 실패했습니다"); else { puts("검색 성공! 아래 요소를 찾았습니다."); printf("x[%d] : %s %dcm %dkg \n", (int)(p - x), p->name, p->height, p->weight); } printf("다시 검색할까요? (1) 예 / (0) 아니오 : "); scanf("%d", &retry); } while (retry == 1); return 0; }
Forums:
https://kldp.org/comment
https://kldp.org/comment/635562#comment-635562
좀 많이 이상한데요 printf("키 : "); 라고
좀 많이 이상한데요 printf("키 : "); 라고 치셨으니 키로 검색을 하고 싶으신거 같은데 그러면 그 값을 temp.name이 아닌 temp.height에 저장해야 되지 않을까요? npcmp함수에도 같은지 아닌지만 알수 있고 바이너리서치에 쓰기에는 부적합하다고 생각하네요. if (x->height > y->height) else 느낌으로 하는 것이 더 좋을거 같습니다.
댓글 달기