好了,所以我想提出一個程序來驗證一個4位數字代碼。C#代碼驗證程序
計算機在一4位代碼生成一個4位代碼的 用戶類型。他們的猜測。 電腦告訴他們有多少數字是 在正確的位置和多少位已被 猜中,但在錯誤的地方猜中。 用戶獲得12個猜測來贏得比賽 - 猜猜正確的代碼。或者 失敗 - 無法猜測。
所以基本上,我的計劃似乎並沒有真正驗證碼是否正確,但我不能明白爲什麼不能因爲我有,如果和循環驗證,請看一看。
class Program
{
public static Random random = new Random();
static void Main(string[] args)
{
int DigitOne = random.Next(0, 10);
int DigitTwo = random.Next(0, 10);
int DigitThree = random.Next(0, 10);
int DigitFour = random.Next(0, 10);
byte[] code = new byte[4];
code[0] = Convert.ToByte(DigitOne);
code[1] = Convert.ToByte(DigitTwo);
code[2] = Convert.ToByte(DigitThree);
code[3] = Convert.ToByte(DigitFour);
bool CodeCorrect = false;
Console.WriteLine(code[0] +""+ code[1] +""+ code[2]+""+code [3]);
Console.WriteLine("You have 12 guesses before you will be permenantly locked out.\n");
int AmountOfGuesses = 0;
while (AmountOfGuesses < 12 && !CodeCorrect)
{
Console.WriteLine("Enter 4 digit code to unlock the safe: ");
int[] UserCode = new int[4];
for (int i = 0; i < 4; i++)
{
UserCode[i] = Convert.ToInt32(Console.Read()) - 48;
}
if (UserCode.Length != 4)
{
Console.WriteLine("Error. Try Again.\n");
}
else
{
int UserDigitOne = UserCode[0];
int UserDigitTwo = UserCode[1];
int UserDigitThree = UserCode[2];
int UserDigitFour = UserCode[3];
for (int i = 0; i < 4; i++)
{
if (UserCode[i] == code[i])
{
Console.WriteLine("The digit at position " + (i + 1) + " is correct.");
}
}
if (UserCode[0] == code[0] && UserCode[1] == code[1] && UserCode[2] == code[2] && UserCode[3] == code[3])
{
CodeCorrect = true;
Console.WriteLine("Code Correct. Safe unlocked.");
}
}
AmountOfGuesses++;
}
if (AmountOfGuesses > 12)
{
Console.WriteLine("Code Incorrect. Safe Locked permenantly.");
}
Console.ReadLine();
}
你有沒有通過代碼加強,看看發生了什麼? – 2014-10-17 18:01:17
是的,我有... – user3063533 2014-10-17 18:01:48
不知道爲什麼你需要使用'byte' ... – crashmstr 2014-10-17 18:04:35