該程式正在從骰子 (1,6) 用戶與敵方計算機中猜測一個數字。所以我的問題是用戶猜測和計算機猜測是否正確。但我被困在運算子 && 不能應用于運算元。
class Program
{
static void Main(string[] args)
{
bool isCorrectGuess = false;
Random random = new Random();
int enemyRandomNum;
int randomNum = random.Next(1, 6);
Console.WriteLine("Welcome to the dice number guessing game!");
Console.WriteLine("A number between 1 and 6 will be generated.");
Console.WriteLine("Who guess the correct number will have 1 point.");
Console.WriteLine("---------------------------------------------------");
while(!isCorrectGuess)
{
Console.WriteLine("Please enter your guess.");
int playerGuess = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("...");
System.Threading.Thread.Sleep(1000);
Console.WriteLine("Enemy AI will now have a guess. ");
Console.WriteLine("...");
System.Threading.Thread.Sleep(1000);
enemyRandomNum = random.Next(1,6);
Console.WriteLine("Enemy AI rolled " enemyRandomNum);
// here is the error
if (playerGuess && enemyRandomNum > randomNum)
{
}
}
}
}
uj5u.com熱心網友回復:
這個:
if (playerGuess && enemyRandomNum > randomNum)
語意上的意思是:
如果
playerGuess為真
并且
enemyRandomNum大于randomNum
但playerGuess 不能是true因為它不是一個布林值,它是一個整數。如果要測驗這兩個值是否都大于,randomNum則需要指定:
if (playerGuess > randomNum && enemyRandomNum > randomNum)
uj5u.com熱心網友回復:
playerGuess是一個整數,但你把它當作一個布林值。嘗試類似的東西
(playerGuess > 0) && (enemyRandomNum > randomNum)
另一種解決方案是您可以轉換playerGuess為布林值。嘗試
bool b = Convert.ToBoolean(playerGuess);
或者
bool b = playerGuess != 0;
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/337221.html
標籤:C#
