바로 게임을 만들기 전에 문자열의 이용, 함수의 활용, 구조체, 배열, 포인터등 연습을 하였다.
아래 소스가 연습의 결과물!
구조체로 ID와 Score를 만든후, 10개의 배열포인터형식으로 만든다.
Score를 중심으로 각 구조체를 qsort함수를 이용하여 퀵정렬을 하고 화면에 출력한다.
프로그램은 Visual Studio 2010 Professinal, Win32 모드에서 코딩 작업.
#include "stdafx.h"
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#define MAX_NUM 10 // 만들 구조체의 갯수를 미리 상수로 지정
// id, score를 Profile구조체로 선언
typedef struct{
int id;
int score;
}Profile;
// 현재 Data를 출력해주는 print함수
void print(const Profile *pro, int n, int s);
// score 정수의 값 크기를 비교해주는 compare함수
int compare (const void * a, const void * b);
// main 함수
int _tmain(int argc, _TCHAR* argv[])
{
Profile *prof;
srand((unsigned)time(NULL));
// Profile구조체 x MAX_NUM(10)만큼의 공간할당 후 prof에 연결
prof = (Profile *)malloc(sizeof(Profile)*MAX_NUM);
// 각 Data를 순차적으로 입력
for (int i = 0 ; i<MAX_NUM ; i++){
prof[i].id = i;
prof[i].score = rand()%100;
}
printf("***** Before *****\n");
print(prof,MAX_NUM, 0);
// stdlib.h 에 있는 qsort를 이용하여 데이터 정렬
qsort(prof,MAX_NUM,sizeof(Profile),compare);
printf("\n");
printf("***** After *****\n");
print(prof,MAX_NUM, 1);
// 할당된 메모리 해제
free(prof);
return 0;
}
int compare (const void * p, const void * q)
{
// 아무타입없는 포인터 p, q를 Profile구조체 형식으로 형변환
const Profile* ip = (const Profile*) p;
const Profile* iq = (const Profile*) q;
// 구조체 안에 있는 score로 값 비교후 리턴
return ip->score - iq->score;
/*
ip - iq
ip가 더 큰 정수의 경우 : + 값 반환
iq가 더 큰 정수의 경우 : - 값 반환
ip와 iq가 같을 경우 : 0 반환
*/
}
static void print(const Profile* pro, int n, int s) {
for(int i=0; i<n; i++){
if(s == 0)
printf("id : %d Score : %d \n", pro[i].id, pro[i].score);
else
printf("Rank : %d \t id : %d Score : %d \n",i+1, pro[i].id, pro[i].score);
}
}
| Unity3D 고급과정 4일차 필기내용 - T아카데미 (0) | 2013.10.12 |
|---|---|
| Unity3D 고급과정 3일차 필기내용 - T아카데미 (0) | 2013.10.10 |
| Unity3D 고급과정 2일차 필기내용 - T아카데미 (0) | 2013.10.09 |
| Unity3D 고급과정 1일차 필기내용 - T아카데미 (4) | 2013.10.08 |
| 게임프로그래밍 수업시작! (0) | 2012.03.05 |
댓글 영역