🎯 計算ゲーム - 解答と解説

課題1-1の要件

1. 完全な解答例

// Visual Studioでの実行を想定したコード #include <stdio.h> #include <stdlib.h> #include <time.h> int main() { // 日本語表示対応 system("chcp 65001"); // 乱数の初期化 srand((unsigned int)time(NULL)); int correct_count = 0; // 正解数 const int MAX_TRIES = 3; // 挑戦回数 printf("=== 計算ゲーム ===\n"); printf("2つの数の和を当ててください!\n\n"); for (int i = 0; i < MAX_TRIES; i++) { // 1-100のランダムな数を2つ生成 int num1 = rand() % 100 + 1; int num2 = rand() % 100 + 1; int correct_answer = num1 + num2; printf("\n問題 %d: %d + %d = ?\n", i + 1, num1, num2); printf("答えを入力してください: "); int user_answer; scanf_s("%d", &user_answer); if (user_answer == correct_answer) { printf("正解です!\n"); correct_count++; } else { printf("不正解... 正解は %d でした\n", correct_answer); } } // 正解率の計算と表示 float accuracy = (float)correct_count / MAX_TRIES * 100; printf("\n=== ゲーム終了 ===\n"); printf("正解数: %d/%d\n", correct_count, MAX_TRIES); printf("正解率: %.1f%%\n", accuracy); return 0; }

2. コードの解説

2.1 必要なヘッダファイル

2.2 重要な変数

2.3 主要な処理の流れ

  1. 初期設定
    • 日本語表示の設定
    • 乱数の初期化
    • 変数の初期化
  2. メインループ(3回)
    • ランダムな数の生成
    • 問題の表示
    • ユーザー入力の受付
    • 正誤判定と結果表示
  3. 最終結果の表示
    • 正解数の表示
    • 正解率の計算と表示

3. 発展的な改良案

よくある間違い