You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#骰子猜数游戏报错:Operator && cannot be applied to 'int'和'bool'操作数

报错原因

&&是C#中的逻辑与运算符,要求左右两侧的运算对象都必须为布尔(bool)类型。你编写的判断条件if (playerGuess && enemyRandomNum > randomNum)中,左侧的playerGuess是int类型的数值,不是布尔值,且C#不支持int到bool的隐式类型转换,因此编译器触发了该报错。

另外补充一个隐藏问题:你当前调用的random.Next(1, 6)生成的是15的整数(`Next`方法的第二个参数为开区间边界,无法取到),如果要实现16的骰子效果,需要修改为random.Next(1, 7)。

修复方案

你需要根据自己的业务逻辑补全playerGuess对应的判断条件,常见的两种业务场景对应的修改如下:

  • 若要判断「玩家和AI猜的数值都大于系统生成的随机数」,修改判断条件为:
if (playerGuess > randomNum && enemyRandomNum > randomNum)
  • 若要判断「玩家和AI都猜对了数值」,修改判断条件为:
if (playerGuess == randomNum && enemyRandomNum == randomNum)

如果你需要其他判断逻辑,只需要把playerGuess对应的部分补全为返回布尔值的比较表达式即可。

完整调整后的代码示例
class Program
{
    static void Main(string[] args)
    {
        bool isCorrectGuess = false;
        Random random = new Random();
        // 记录玩家和AI分数
        int playerScore = 0;
        int enemyScore = 0;

        // 修改为生成1~6的随机数
        int randomNum = random.Next(1, 7);

        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);

            int enemyRandomNum = random.Next(1,7);
            Console.WriteLine("Enemy AI rolled " + enemyRandomNum);

            // 判断双方猜中情况,加分
            bool playerRight = playerGuess == randomNum;
            bool enemyRight = enemyRandomNum == randomNum;
            if (playerRight)
            {
                playerScore++;
                Console.WriteLine($"你猜对了!当前分数:{playerScore}");
            }
            if (enemyRight)
            {
                enemyScore++;
                Console.WriteLine($"AI猜对了!AI当前分数:{enemyScore}");
            }
            // 只要有人猜对就重置随机数,继续游戏,这里可以根据需求调整是否结束
            if (playerRight || enemyRight)
            {
                randomNum = random.Next(1,7);
                Console.WriteLine("生成新的1~6随机数,游戏继续");
            }
        }
    }
}

内容的提问来源于stack exchange,提问作者Mc Dz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 18:36:03