• 카테고리

    질문 & 답변
  • 세부 분야

    프로그래밍 언어

  • 해결 여부

    미해결

while(1)

18.07.15 14:17 작성 조회수 177

0

shuffleAnimal 함수에서 getEmptyPosition 함수를 호출하면, getEmptyPosition 함수에서는 while(1)이 돌아가게 되잖아요. 그러면 무한루프때문에 계속 빈 좌표값은 출력하지만, loop를 빠져나오지 못하고 빙빙 돌게되는거 아닌가요?

답변 3

·

답변을 작성해보세요.

1

안녕하세요 나도코딩입니다 ^^

첫 번째 질문은,

if (arrayAnimal[x][y] == -1)

{

return randPos;

}

라는 탈출 구문을 통해서 빈 자리를 찾게 되면 해당 자리 좌표를 반환하며 무한 루프를 탈출하게 됩니다. 만약 빈 자리가 없다고 하면 계속해서 반복문이 수행 되겠지만, 그렇다는 것은 앞쪽에서 이미 어딘가 코드가 잘못되었다는 얘기가 됩니다. 자리의 갯수는 정해져 있으니까요.

두 번째 질문의 코드에서는

  1. 같은 동물 발견 시 출력하는 배열 값이 잘못 되었구요,

    printf("nn빙고! : %s 발견!nn", arrayAnimal[firstSelect_x][firstSelect_y]);

    -> strAnimal[arrayAnimal[firstSelect_x][firstSelect_y]]);

  2. 퀴즈를 출력하는 함수에 필요한 연산이 누락되었네요
  3. else

    {

    printf("%8d", seq);

    }

    seq++; // 연산

    }

    printf("n"); // 줄바꿈

위 두 부분 수정 후 다시 한 번 확인해볼까요? ^^

0

코드가 이상하게 복붙이 되네요...ㅠㅠㅠㅠ

0

이어서 질문드리려고 합니다. 강의를 들으면서 코드를 다 짜보았는데, 원인을 알수 없지만 실행이 되지 않습니다.. 나름대로 디버깅을 해본 결과, shuffleAnimal 함수에서 이상이 발생한 듯 싶습니다. while(1)이 빙빙 돌아서 결과가 안나오는건가 싶기도 합니다. 코드를 한번 봐주시면 감사할 것 같습니다.

include

include

//10마리의 서로 다른 동물(각 카드 2장씩)
//사용자로부터 2개의 입력값을 받아서 -> 같은 동물 찾으면 카드 뒤집기
//총 실패 횟수 알려주기
int arrayAnimal[4][5];//20장의 카드
int checkAnimal[4][5];//뒤집혔는지 여부 확인
char *strAnimal[10]; //character pointer 형
void initAnimalArray();
void initAnimalName();
void shuffleAnimal();
int getEmptyPosition();
void printAnimals();
void printQuestion();
int conv_pos_x(int x);
int conv_pos_y(int y);
int foundAllAnimals();
int main(void) {
srand(time(NULL));

initAnimalArray();
initAnimalName();

shuffleAnimal();

int failCount = 0;//실패 횟수

while (1) {
    int select1 = 0;//사용자가 선택한 처음 수
    int select2 = 0;//사용자가 선택한 두번째 수

    printAnimals();//동물 위치 출력
    printQuestion();//문제 출력
    printf("뒤집을 카드를 2개 고르세요");
    scanf_s("%d %d", &select1, &select2);

    if (select1 == select2) {
        continue;//같은 카드 선택시 무효
    }

    //좌표에 해당하는 카드를 뒤집어보고 같은지 안같은지 확인

    //정수 좌표를 (x,y)로 변환
    int firstSelect_x = conv_pos_x(select1);
    int firstSelect_y = conv_pos_y(select1);

    int secondSelect_x = conv_pos_x(select2);
    int secondSelect_y = conv_pos_y(select2);

    if ((checkAnimal[firstSelect_x][firstSelect_y] == 0 //같은 동물인 경우
        && checkAnimal[secondSelect_x][secondSelect_y] == 0)
        && (arrayAnimal[firstSelect_x][firstSelect_y]
            == arrayAnimal[secondSelect_x][secondSelect_y])) {
        printf("\n\n빙고! : %s 발견!\n\n", arrayAnimal[firstSelect_x][firstSelect_y]);
        checkAnimal[firstSelect_x][firstSelect_y] = 1;
        checkAnimal[secondSelect_x][secondSelect_y] = 1;//선택된 카드라고 바꿈.
    }
    else {
        printf("\n\n 땡!!(틀렸거나, 이미 뒤집힌 카드입니다!!)\n");
        printf("%d : %d\n", select1, strAnimal[arrayAnimal[firstSelect_x][firstSelect_y]]);
        printf("%d : %d\n", select1, strAnimal[arrayAnimal[secondSelect_x][secondSelect_y]]);
        printf("\n\n");

        failCount++;
    }
    //모든 동물을 찾았는지 여부 1:참,0:거짓
    if (foundAllAnimals() == 1) {
        printf("\n\n===축하합니다!! 모든 동물을 다 찾았네요!!==\n\n");
        printf("지금까지 총 %d번 실수하셨습니다.", failCount);
        break;
    }

}

return 0;

}
void initAnimalArray() {
for (int i = 1; i < 4; i++) {
for (int j = 1; j < 5; j++) {
arrayAnimal[i][j] = -1;
}
}
}
void initAnimalName() {
strAnimal[0] = "원숭이";
strAnimal[1] = "하마";
strAnimal[2] = "강아지";
strAnimal[3] = "고양이";
strAnimal[4] = "돼지";
strAnimal[5] = "코끼리";
strAnimal[6] = "기린";
strAnimal[7] = "낙타";
strAnimal[8] = "타조";
strAnimal[9] = "호랑이";
}
void shuffleAnimal() {
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 2; j++) {
int pos = getEmptyPosition();
int x = conv_pos_x(pos);
int y = conv_pos_y(pos);

        arrayAnimal[x][y] = i;
    }
}

}
//좌표에서 빈공간 찾기
int getEmptyPosition() {
while (1) {
int randPos = rand() % 20;//0~19사이의 수
int x = conv_pos_x(randPos);
int y = conv_pos_y(randPos);

    if (arrayAnimal[x][y] == -1) {
        return randPos;
    }
}
return 0;

}
int conv_pos_x(int x){
return x / 5;//x를 5로 나눈 몫
}
int conv_pos_y(int y){
return y % 5;//y를 5로 나눈 나머지
}
void printAnimals() {
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 5; j++) {
printf("%8s", strAnimal[arrayAnimal[i][j]]);
}
printf("n");
}
printf("n==================================n");
}
void printQuestion() {
printf("nn(문제)nn");
int seq = 0;

for (int i = 0; i < 4; i++) {
    for (int j = 0; j < 5; j++) {
        //카드를 뒤집어서 정답을 맞췄으면 동물 이름
        if (checkAnimal[i][j] != 0) {
            printf("%8s", strAnimal[arrayAnimal[i][j]]);

        }
        //아직 못맞췄으면 숫자
        else {
            printf("&8s", seq);
        }
    }
}

}
int foundAllAnimals() {
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 5; j++) {
if (checkAnimal[i][j] == 0) {//못찾은 동물이 있음
return 0;
}
}
}
return 1; //모두 다 찾음
}