2015.12.08 Xcode-猜数字
1 #include <stdio.h> 2 3 #include <stdlib.h> 4 5 #include <time.h> 6 7 #include <stdbool.h> 8 9 10 11 void productArray(int array[]); 12 13 void bubbleSort(int array[]); 14 15 void isCorrect(); 16 17 18 19 int main(int argc, const char * argv[]) { 20 21 int array[4] = {}; 22 23 24 25 productArray(array); 26 27 bubbleSort(array); 28 29 isCorrect(array); 30 31 32 33 return 0; 34 35 } 36 37 38 39 //生成随机数组 40 41 void productArray(int array[]){ 42 43 int temp; 44 45 int isExist = false; 46 47 48 49 srand((unsigned int)time(NULL)); //时间做“种子”,这样生成的数组就是完全随机的 50 51 52 53 for (int i = 0; i < 4; i++) { 54 55 temp = rand() % 9 + 1; 56 57 58 59 for (int j = 0; j < i ; j++) { 60 61 if (array[j] == temp) { 62 63 isExist = true; 64 65 } 66 67 } 68 69 70 71 if (isExist == true) { 72 73 i--; 74 75 isExist = false; 76 77 }else { 78 79 array[i] = temp; 80 81 } 82 83 } 84 85 } 86 87 88 89 //排序 90 91 void bubbleSort(int array[]){ 92 93 int temp; 94 95 96 97 for (int i = 0; i < 4; i++) { 98 99 for (int j = 2; j >= i; j--) { 100 101 if (array[j] > array[j + 1]) { 102 103 temp = array[j]; 104 105 array[j] = array[j + 1]; 106 107 array[j + 1] = temp; 108 109 } 110 111 } 112 113 } 114 115 } 116 117 118 119 120 121 void isCorrect(int array[]){ 122 123 int inputedArray[4] = {}; 124 125 int countA = 0; 126 127 int countB = 0; 128 129 int totalWrongTime = 10; 130 131 int wrongTime = 0; 132 133 134 135 do { 136 137 printf("请输入四个数字:"); 138 139 140 141 for (int i = 0; i < 4; i ++) { 142 143 scanf("%d", &inputedArray[i]); 144 145 } 146 147 148 149 for (int i = 0; i < 4; i ++) { 150 151 for (int j = 0; j < 4; j ++) { 152 153 if (array[i] == inputedArray[j]) { 154 155 if (i == j) { 156 157 countA ++; 158 159 }else { 160 161 countB ++; 162 163 } 164 165 } 166 167 } 168 169 } 170 171 172 173 if (countA == 4) { 174 175 printf("Congratulations!\n"); 176 177 break; 178 179 }else { 180 181 printf("%dA%dB\n", countA, countB); 182 183 wrongTime ++; 184 185 countB = 0; 186 187 countA = 0; 188 189 } 190 191 192 193 } while (wrongTime < totalWrongTime); 194 195 }