2017-05-09 4 views
0

私はコーディングとC++のやや新しいです。私は、試行が失敗するたびに表示される配列に前の推測を格納する推測ゲームを作ろうとしました。単純な推測ゲームの最後の試行でX変数が変更されました。C++

問題は、私が入力しても、3回目の試行は常に正しく登録され、乱数であるx変数はy [2]として入力されたものに変わります。このコードは、配列をy変数に追加する前に完全に機能し、残りのコードをそれに合わせて調整しました。

また、変数をデバッグしようとしました。すべての助けは大いに感謝しています。ありがとう! ;)

//Generating Random Number: 

#include <cstdlib> // or <stdlib.h> 
#include <ctime> // or <time.h> 
#include <iostream> 
#include <windows.h> 

using namespace std; 

int main() 
{ 
    int x; 
    int y[2]; 
    int z = 3; 
    int i; 
    bool done = false; 
    srand(time(NULL));  
    x = rand() % 10 + 1; 
    i = 0; 
    int s; 
    s = x; 
    while (done == false) 
    { 
     cout << "Guess a number between 1 to 10.\n"; 
     switch (i) 
     { 
      case 0: break; 
      case 1: 
       cout << "Previous guesses:\n" << y[0] << endl << endl; break; 
      case 2: 
       cout << "Previous guesses:\n" << y[0] << endl << y[1] << endl << endl; break; 
     } 
     cin >> y[i]; 
     cout << "y[" << i << "] = " << y[i] << endl; 
     cout << "s = " << s << endl; 
     if (y[i] > s) 
     { 
      z--; 
      i++; 
      cout << "\nLower!\n" << "Tries remaining: " << z << endl << endl; 
      if (z == 0) 
      { 
       cout << "\nSorry! You ran out of tries. :("; 
       Sleep (2000); 
       done = true; 
      } 
     } 
     else if (y[i] < s) 
     { 
      z--; 
      i++; 
      cout << "\nHigher!\n" << "Tries remaining: " << z << endl << endl; 
      if (z == 0) 
      { 
       cout << "\nSorry! You ran out of tries. :("; 
       Sleep (2000); 
       done = true; 
      } 
     } 
     else if (y[i] == s) 
     { 
      cout << "i = " << i << endl; 
      cout << "\nCongratulations!\n" << "Your number is " << y[i] << ".\n" << "Tries remaining: " << z; 
      done = true; 
     } 
    } 
    return(0); 
} 
+1

とき '私== 2'、' Y –

+0

奇数が、私は配列は0としてそれを考えるだろうと思った範囲外の書き込み '[I] 、1、2となり、3つの要素になります。これはプログラムに必要なすべてです。それはうまくいった。どうもありがとう! – Elairion

+0

すべての警告とデバッグ情報([GCC](http://gcc.gnu.org/)を使用している場合は 'g ++ -Wall -Wextra -g')を使用してコンパイルします。その後**デバッガを使用します**( 'gdb') –

答えて

0

は、サイズが2(2つの要素を保持できる)の配列を作成することを意味します。以上、vectorまたはstd::arrayは、アレイに組み込まれてより好ましい何

関連する問題