C
// コードは一部省略しています. 完全版は一番下にあります. B_H check(const char ans[], const char num[]) { printf("ans %s\n", ans); // check 1 printf("num %s\n", num); // check 2 } int main(void) { char ans[DIG]; char num[DIG]; create_num(ans); // ans[i]に数字文字('0'~'9')を代入 i=0~DIG printf("%s\n", ans); // main 1 while (bh.hit != DIG) { scanf("%s", num); bh = check(ans, num); // main 2 } return 0; }
main関数内の// main 1
ではcreate_num関数で代入した数字文字の文字列が正しく表示されますが,//main 2
で配列ansをcheck関数へ渡そうとしても,正常に渡せません.
すなわち//check 1
の部分が表示されません("ans "と空白になる).
一方,//check 2
の部分では,numの値ーmain関数のwhile文内のscanfで入力した値ーが正しく表示されます.
どうして,配列ansを関数checkへ正しく渡せていないのですか?
ご回答のほどよろしくお願いします.
なお,実行環境はmacOS 10.15のApple clang version 12.0.0 (clang-1200.0.32.29)です.
C
// 完全版 #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <limits.h> #include <time.h> #define DIG 4 typedef struct { int blow; int hit; } B_H; int sleep(unsigned long x) { clock_t c1 = clock(), c2; do { if ( (c2 = clock()) == (clock_t)-1) return -1; } while (1000.0*(c2-c1) / CLOCKS_PER_SEC < x); return 1; } int create_num(char ans[]) { int r; int i = 1; int flag = 1; srand(time(NULL)); if (DIG > 9) return -1; ans[0] = (rand() % 10) + '0'; while (i < DIG) { flag = 1; ans[i] = (rand() % 10) + '0'; for (int j = 0; j < i; j++) { if (ans[j] == ans[i]) { flag = 0; break; } } if (flag) i++; } return 1; } B_H check(const char ans[], const char num[]) { B_H bh; bh.blow = 0; bh.hit = 0; printf("ans %s\n", ans); printf("num %s\n", num); for (int i = 0; i < DIG; i++) { for (int j = 0; j < DIG; j++) { if (ans[i] == num[j]) { bh.blow++; if (i == j) bh.hit++; break; } } } printf("blow%d\nhit%d\n", bh.blow,bh.hit); return bh; } int put(B_H bh) { putchar('\n'); if (bh.hit == DIG) { puts("正解!"); return 1; } else if (bh.blow == 0) puts("どの数字も含まれません."); else { printf("それらの数字中%d個の数字が含まれます.\n", bh.blow); if (bh.hit) printf("その中の%d個は位置もあっています.\n", bh.hit); else puts("ただし位置もあっている数字はありません."); } return 0; } int main(void) { char ans[DIG]; char num[DIG]; B_H bh; bh.blow = 0; bh.hit = 0; int n = 0; int cnt; create_num(ans); printf("%s\n", ans); while (bh.hit != DIG) { printf("\n重複のない%d桁の数字を当ててください : ", DIG); scanf("%s", num); bh = check(ans, num); put(bh); } return 0; }
まだ回答がついていません
会員登録して回答してみよう