运营商“||”不能应用于'bool'和'int'类型的操作数

时间:2017-02-24 15:08:38

标签: c#

我对C#很新,并尝试制作文本库主脑,但是当我尝试检查用户的回答是否与3个数字相同时,我得到了这个错误。 “运算符”||“不能应用于'bool'和'int'类型的操作数”

        Random rnd = new Random();

        int pos1 = rnd.Next(1, 6);  //generates random numbers
        int pos2 = rnd.Next(1, 6);
        int pos3 = rnd.Next(1, 6);
        int pos4 = rnd.Next(1, 6);

        int answer1 = Convert.ToInt32(Console.ReadLine());

        if (asnwer1 == pos1)           //checks if answer is the same as pos1
        {
            Console.WriteLine("Right");
        }
        else if (answer1 == pos2 || pos3 || pos4)
        {
            Console.WriteLine("Wrong");
        }
        else {
            Console.WriteLine("Nope");

5 个答案:

答案 0 :(得分:5)

所有条件都应返回bool结果。 pos3pos4int - 您应该与answer1进行比较。

您应该重写else if

else if (answer1 == pos2 || answer1 == pos3 || answer1 == pos4)

答案 1 :(得分:1)

if (new[] {pos2,pos3,pos4}.Contains(answer1))

答案 2 :(得分:0)

待办事项

else if (answer1 == pos2 || answer1 == pos3 || answer1 == pos4)

理想情况下,您的代码应为

Console.WriteLine(answer1 == pos1 ? "Correct": "Incorrect");

答案 3 :(得分:0)

||等逻辑运算符要求您双方都bool ean值left || right。在您的示例中,您有第一个类型为bool的操作数,其次是int个egers。这没有任何意义。

为了能够比较你的答案是否等于这三个值,你必须在类似条件的陈述(answer == posX)中使用它们,其中X是你的位置号码。

你的工作代码示例:

else if (answer1 == pos2 || answer1 == pos3 || answer1 == pos4 )
// do some logic here ...

将此扩展为更多" generic"方式,每个操作数必须提供bool ean值:

if ( true || false || ... )

但是因为将原始bool ean值打包成这样的内容并不会有所帮助:

bool a = answer1 == pos2;
bool b = answer1 == pos3;
if ( a || b ... )

您实际上可以编写类似您尝试过的条件:

if ( operandL == operandR || operandL != operandR || ... )

答案 4 :(得分:0)

我认为,

 else if (answer1 == pos2 || pos3 || pos4)

你的意思是" answer1等于pos2,pos3或pos4"。

但是,这不是正确的语法。正如错误消息所述,它期望||内的所有内容都是布尔表达式,而pos3pos4肯定不是布尔值。

您可以编写如下的扩展方法:

public static class Extensions
{
    public static bool In<T>(this T item, params T[] args)
    {
        foreach (T arg in args)
        {
            if (arg.Equals(item))
                return true;
        }

        return false;
    }
}

或者更简单:

public static class Extensions
{
    public static bool In<T>(this T item, params T[] args)
    {
        return args.Contains(item);
    }
}

然后你可以写answer1.In(pos2, pos3, pos4)

相关问题