【问题标题】:Operator && cannot be applied to operands of type 'int' and 'bool'运算符 && 不能应用于“int”和“bool”类型的操作数
【发布时间】:2021-10-26 22:56:16
【问题描述】:

该程序正在从骰子 (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)
            {

            }


        }


    }
}

【问题讨论】:

  • playerGuess 的类型为 int。您不能直接在条件语句中使用它。使用playerGuess > 0左右。

标签: c#


【解决方案1】:

这个:

if (playerGuess && enemyRandomNum > randomNum)

语义上的意思:

如果playerGuess 为真
并且
enemyRandomNum 大于 randomNum

但是playerGuess 不能true,因为它不是布尔值,而是整数。如果您要测试 both 是否大于randomNum,那么您需要指定:

if (playerGuess > randomNum && enemyRandomNum > randomNum)

【讨论】:

  • Joel 我将编辑代码。请多多包涵。我需要显示谁猜对了,将进行 5 场比赛,达到 5 分的人将赢得比赛。
  • 请查看更新后的代码。
  • @Joel Coehoorn 请查看更新后的代码。
  • @McDz:如果您有新问题要问,最好发布一个全新的问题。修改此问题中的代码,使其不再包含您所询问的问题,这会使问题变得混乱且对未来的读者没有帮助。
  • 好吧对不起我的错。谢谢!
【解决方案2】:

playerGuess 是一个整数,但您将其视为布尔值。尝试类似

(playerGuess > 0) && (enemyRandomNum > randomNum)

另一个解决方案是您可以将playerGuess 转换为布尔值。试试

bool b = Convert.ToBoolean(playerGuess);

bool b = playerGuess != 0;

【讨论】:

  • 谢谢! @eglease
猜你喜欢
  • 2015-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多