原代碼縮排全無、變數命名無意義 (`w,b,g,m,n...`)、`goto` 濫用、`rand()` 種子重複、`scanf` 缺錯誤處理,導致每次重新猜測結果異常。
#include
#include
#include
#include
#include
void genSecret(int s[4]);
void judge(const int s[4], const int g[4], int *A, int *B);
bool validInput(const char *str, int g[4]);
int main() {
srand((unsigned)time(NULL));
int secret[4]; genSecret(secret);
int guess[4], A, B, attempts = 0;
char buf[16];
while (true) {
printf("請輸入 4 位不重複數字 (q 退出): ");
if (!fgets(buf, sizeof(buf), stdin)) break;
buf[strcspn(buf, "\n")] = 0;
if (strcmp(buf, "q") == 0) break;
if (!validInput(buf, guess)) { puts("格式錯誤"); continue; }
++attempts;
judge(secret, guess, &A, &B);
printf("%dA%dB\n", A, B);
if (A == 4) { printf("恭喜!共猜 %d 次。\n", attempts); break; }
}
return 0;
}
// 實作 genSecret, judge, validInput 略
重寫比修補快:套用標準結構、函式分離、有意義命名,代碼行數減半、Bug 歸零。