fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. int cmp(const void* n1, const void* n2) {
  5. if(*(int *)n1 > *(int *)n2) {
  6. return -1;
  7. } else if (*(int *)n1 < *(int *) n2) {
  8. return 1;
  9. } else {
  10. return 0;
  11. }
  12. }
  13.  
  14. int main(void) {
  15. char buffer[5];
  16. printf("データ数 : ");
  17. scanf("%4s%*[^\n]", buffer);
  18. int num = strtol(buffer, NULL, 10);
  19. int* score = (int*)malloc(sizeof(int) * num);
  20. for (int i = 0; i < num; i++) {
  21. printf("%dつめの点数 : ", i + 1);
  22. scanf("%4s%*[^\n]", buffer);
  23. score[i] = strtol(buffer, NULL, 10);
  24. }
  25. qsort(score, num, sizeof(int), cmp);
  26. puts("*** ソート済みのデータ(降順) ***");
  27. for (int i = 0; i < num; i++) {
  28. printf("%dつ目の点数 : %d\n", i + 1, score[i]);
  29. }
  30. scanf("%4s%*[^\n]", buffer);
  31. int key = strtol(buffer, NULL, 10);
  32. int* result = bsearch(&key, score, num, sizeof(int), cmp);
  33. if (result != NULL) {
  34. printf("%ld\n", result - score + 1);
  35. }
  36. free(score);
  37. return EXIT_SUCCESS;
  38. }
  39.  
Success #stdin #stdout 0s 5548KB
stdin
Standard input is empty
stdout
データ数 : *** ソート済みのデータ(降順) ***