数当てゲーム-3~999の3の倍数を当てる(accepted編)-【C言語】

数当てゲーム-3~999の3の倍数を当てる(accepted編)-

#include <stdio.h>
#include <time.h>
#include <stdlib.h>

#define MAX_STAGE 9

int main(void) {
  int i;
  int no;
  int ans;
  int accepted = 0;
  int count = 0;
  int stage = MAX_STAGE;

  srand(time(NULL));
  ans = (1 + rand() % 334) * 3;

  printf("%d回以内で3以上999以下の3の倍数を当ててください。\n", stage);

  while (stage > 0) {

    accepted = 0;

    while (accepted == 0)
    {
      printf("いくつかな:");
      scanf("%d", &no);


      if (no % 3 != 0)
      {
        printf("3の倍数を入力してください\n");
      }
      else {
        accepted = 1;
      }
    }

    stage--;

    if (ans < no) {
      printf("もっと小さいよ。\n\n");
    }
    else if (ans > no) {
      printf("もっと大きいよ。\n\n");
    }
    else {
      break;
    }

    if (stage > 0){
      printf("あと%d回。\n", stage);
    }
  }

  if (ans == no) {
    printf("正解です!%d回で当たりましたね。", MAX_STAGE - stage);
  }
  else {
    printf("残念。正解は%dでした。", ans);
  }

  return 0;
}

▷accepted(フラグ)

while (stage > 0) {

  accepted = 0;

  while (accepted == 0)
  {
    printf("いくつかな:");
    scanf("%d", &no);


    if (no % 3 != 0)
    {
      printf("3の倍数を入力してください\n");
    }
    else {
      accepted = 1;
    }
  }

変数acceptedをフラグとして使い、3の倍数を入力されているかの判断をする。

コメントを残す

あなたのメールアドレスは公開されません。必須項目には印がついています *