2017-02-08 8 views
0

私は1から20までの数字を推測するユーザーのコードに取り組んでいます。それは一度推測されたそれぞれの数だけをカウントするように私はそれをどのように編集することができますか?ここで私がこれまで持っているものです。同じ推測を2回カウントしないcでの数字ゲームを推測します

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

int main(void) 
{ 
    srand(time(NULL)); 
    int r = rand() %20 + 1; 
    int guess; 
    int correct = 0; 
    int count = 0; 

    printf("Let's play a number guessing game!\n"); 
    printf("Guess a number between 1 and 20.\n"); 


    do 
    { 
     scanf("%d", &guess); 

     if (guess == r) 
     { 
      count++; 
      printf("Congrats! you guessed the right answer in %d attempts!\n", count); 
      correct = 1; 
     } 

     if (guess < r) 
     { 
      count++; 
      printf("Too low, try again.\n"); 
     } 

     if (guess > r) 
     { 
      count++; 
      printf("Too high, try again.\n"); 
     } 
    } 
    while (correct == 0); 

    return 0; 
} 

答えて

1

あなたは数が繰り返されるかどうかを検出するために、ルックアップテーブルを使用することができます。

int used[21] = {0}; 

do 
{ 
    scanf("%d", &guess) 
    if (guess < 1 || guess > 20) { 
     puts("pssst ... from 1 to 20"); 
     continue; 
    } 
    if (used[guess] == 1) { 
     puts("Repeated!"); 
     continue; /* without counting */ 
    } else { 
     used[guess] = 1; 
    } 
    ...