猜一個四位數字(千位數不為0,且沒有數字重複)
它會提示有幾A幾B
ex: 2A1B
2A代表有2個數值猜對且位置正確
1B代表有1個數值猜對但位置不正確
以下為code
#include <iostream>
#include <cstdlib>
#include <sstream>
#include <time.h>
using namespace std;
//把整數轉為字串的副程式IntToString
string IntToString (int N)
{
string Get;
stringstream ss;
ss << N;
ss >> Get;
return Get;
}
int main()
{
string Answer; //儲存答案
string Guess; //儲存使用者猜的數字
int Num; //儲存由rand()產生的亂數
int A = 0;
int B = 0;
int Time = 5; //一個回合可以猜的次數
int Round = 1; //回合數 初始值 = 1
srand(time(NULL));
while(true)
{
Answer = IntToString(rand()%9+1); //先將答案的千位數字指定為1~9之間的任意數字
for (int i=1; i<4; i++)
{
//產生謎底
Num = rand()%10;
if(Answer.find(IntToString(Num)) == -1)
{
Answer = Answer + IntToString(Num);
}
else
{
i--;
}
}
cout << "----------------------" << endl;
cout << "Round " << Round << endl; //提示目前回合
cout << endl;
while(true)
{
//將A與B值初始化
A = 0;
B = 0;
//使用者猜數字
cout << "請猜一個四位數字: ";
getline(cin,Guess);
//判斷幾A幾B
for (int i=0; i<4; i++)
{
for (int j=0; j<4; j++)
{
if((Answer[i] == Guess[j])&&(i == j))
{
A++; //值吻合且位置相同
}
else if((Answer[i] == Guess[j])&&(i != j))
{
B++; //值吻合但位置不同
}
}
}
//輸出提示
if (A == 4)
{
cout << "恭喜答對!" << endl;
break;
}
else if((A != 4)&&(Time > 1))
{
Time--;
cout << A << "A" << B << "B" << endl;
cout << "尚餘 " << Time << " 次機會..." << endl;
cout << endl;
//Debug過程用
//cout << Answer << endl;
}
else
{
break;
}
}
//
cout << A << "A" << B << "B" << endl;
cout << endl;
cout << "正確解答: " << Answer << endl;
Round++;
Answer = "";
Guess = "";
Time = 5;
}
return 0;
}
沒有留言:
張貼留言