1. 程式人生 > >遊戲系列~猜數字(4)

遊戲系列~猜數字(4)

輸入 welcom while lease define ice input namespace wan

#include <cstdlib>
#include <cmath>
#include <ctime>
#include <iostream>
using namespace std;
#define NUM 4
// 隨機產生4個數字,作為答案供使用者猜測
void answer(int *a, int s)
{
int i, j;
srand(time(NULL));
for (i = 0; i < s; ++i)
{
a[i] = rand()%10;
// 確保當前產生的隨機數與前面產生的不同
for (j = 0; j < i; ++j)
if (a[i] == a[j])
{
a[i] = rand()%10;
j = -1;
continue;
}
}
}
int main(void)
{
int a[NUM], g[NUM]={0, 0, 0, 0}, i, j, n, x, y;
char choice;
answer(a, NUM);
cout << "***Welcome To This Little Game***" << endl << endl;
cout << "Please input a 4-digit number: " << endl;
while (1)
{
x = y = 0;
i = NUM-1;
do
{
cin >> n;
} while (n < 0 || n > 9999); // 判斷用戶輸入的數字是否有效,無效重新接收輸入
// 分解數字
while (n)
{
g[i--] = n%10; n /= 10;
}
// 驗證輸入
for (i = 0; i < NUM; ++i)
{
if (a[i] == g[i])
x += 1;
else
{
for (j = 0; j < NUM; ++j)
if (a[i] == g[j])
y += 1;
}
}
// 判斷輸入數字是否猜對
if (4 == x)
{
cout << "Congratulations!" << endl;
break;
}
else
{
cout << "Sorry, you haven‘t guess the right number!" << endl;
cout << x << ‘A‘ << y << ‘B‘ << endl;
cout << "Do you want to continue(y or n)?" << endl;
cin >> choice;
if (choice != ‘y‘ && choice != ‘Y‘)
{
cout << "Right number is:" << a[0] << a[1] << a[2] << a[3] << endl;
break;
}
}
}
cout << "exiting.." << endl;
}

遊戲系列~猜數字(4)