猜數字遊戲,電腦亂數產生不重複的四位數字,由使用者猜,如電腦亂數為5137,猜1234,則輸出1A1B,A代表數字與位置都對,B代表數字對,但位置不對。
#include <stdio.h> #include <stdlib.h> #include <time.h> #define DIGIT 4 void produce_number(int number[]); int check_answer(int number[],int user_answer[],int& same_letter_place,int& same_letter); void input_convert(int number[],int input_number); void main(void) { for(;;) { int number[DIGIT],user_answer[DIGIT],user_input,tsuzuku=1; char play=0; produce_number(number); //-------測試用-------- /*for(int i=0;i<DIGIT;i++) printf("%d\t",number[i]); printf("\n");*/ //-------測試用-------- while(tsuzuku) { int a=0,b=0; printf("please enter 4-digits number >"); scanf("%d",&user_input); input_convert(user_answer,user_input); tsuzuku=check_answer(number,user_answer,a,b); printf("%dA%dB\n",a,b); } printf("you got it !! play again ? [Y/N]"); while(play != 'n' && play != 'N' && play != 'y' && play != 'Y') play=getchar(); if(play == 'n' || play == 'N') break; } printf("Bye! Bye!"); system("pause"); } void produce_number(int number[]) { srand(time(NULL)); int i=1; number[0]=1+rand()%9; while(i < DIGIT) { int temp=1+rand()%9,test_result=1; for(int j=0;j<i;j++) if(temp==number[j]) test_result=0; if(test_result) { number[i]=temp; i++; } } } int check_answer(int number[],int user_answer[],int& same_letter_place,int& same_letter) { for(int i=0;i<DIGIT;i++) for(int j=0;j<DIGIT;j++) if(user_answer[i]==number[j]) same_letter++; for(int k=0;k<DIGIT;k++) if(user_answer[k]==number[k]) same_letter_place++; same_letter=same_letter-same_letter_place; if(same_letter_place==DIGIT) return 0; else return 1; } void input_convert(int number[],int input_number) { for(int i=DIGIT-1;i>=0;i--) { number[i]=input_number%10; input_number/=10; } }
沒有留言:
張貼留言