0
我對編碼和C++以及所有人都有些新意。我試圖做出一個猜謎遊戲,將以前的猜測存儲在數組中,每次嘗試失敗後都會顯示。簡單猜謎遊戲的最後一次嘗試的X變量變化,C++
問題是,無論我輸入什麼,第三次嘗試總是會註冊爲正確的,隨機數的x變量將更改爲我輸入的任何y [2]。在將數組添加到y變量之前,代碼完美工作,並調整了其餘代碼以適應該變量。
我也cout-ed變量來嘗試調試它。任何和所有的幫助,非常感謝。謝謝! )
//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);
}
當'我== 2','值Y [i]'寫出界 –
奇怪,我以爲陣列將其視爲0 ,1和2,因此使它成爲3個元素,這是程序所需要的。它確實工作。非常感謝! – Elairion
編譯所有警告和調試信息(如果使用[GCC](http://gcc.gnu.org/),則編譯'g ++ -Wall -Wextra -g')....然後**使用調試器**('gdb') –