![](/img/trans.png)
[英]CS0019 Operator cannot be applied to operands of type 'bool' and 'int'
[英]CS0019 C# Operator '||' cannot be applied to operands of type 'int' and 'int'
我有一個帶有整數的 or 運算符 (||) 但由於某種原因它給了我一個錯誤。 整數是位置。 我想跟蹤玩家的位置,這樣我就可以在一段代碼中控制所有動作。 看起來像if (location == (1 || 2 || 3)
給了我錯誤。
Actions:
Console.WriteLine("");
Console.Write("What should i do? ");
string move = Console.ReadLine();
if (move.Contains("north"))
{
if (location == (1 || 2 || 3))
{
Console.WriteLine("There is a cliff here I cant climb up!");
}
}
else if (move.Contains("east"))
{
if (location == (3 || 6 || 9))
{
Console.WriteLine("There is a cliff here I cant climb up!");
}
}
else if (move.Contains("south"))
{
if (location == (7 || 8 || 9))
{
Console.WriteLine("There is a cliff here I cant climb up!");
}
}
else if (move.Contains("west"))
{
if (location == (1 || 2 || 3))
{
Console.WriteLine("There is a cliff here I cant climb up!");
}
}
else if (move.Contains("grab"))
{
if (location == (6))
{
Console.WriteLine("I don't have time for apples!");
}
else if (location == (8))
{
Console.WriteLine("It's locked!");
}
else if (location == (1 ||2 || 4 || 5 || 7 || 9))
{
Console.WriteLine("There is nothing to grab!");
}
else if (location == (3))
{
Console.WriteLine("I grabbed the key.");
bool key = true;
}
}
else if (move.Contains("use"))
{
}
謝謝你的幫助。
應該是這樣的:
if(location == 1 || location == 2 || location == 3)
我的印象是,您應該更加熟悉編程語言與自然語言不同的事實。
在自然語言中,您會說“如果那個數字是 1 或 2 或 3,請做某事”,每個人都會理解您。
另一方面,編程語言主要建立在邏輯和算術上。 如果機器(編譯器)可以將一組有限的規則應用於您編寫的內容,那么它更容易理解您想要什么。
如果它有更多規則,它可能會給你額外的選項來寫“location == (1 || 2 || 3)”並將其轉換為其他答案告訴你寫的內容。
這種方法的缺點是,這個額外的選項很可能會引入你最終可能會稱之為模棱兩可或矛盾的東西,你寫其他東西,編譯器會把它翻譯成你從未預料到的東西。
這種情況下的規則基本很明確:
總結一下:編譯錯誤表明您還沒有理解編譯器如何解釋語言結構。
您不能以這種方式編寫條件,而是使用:
if (location == 7 || location == 8 || location == 9 )
或者,如果您願意,也可以改用switch
語句。
在 C# 中,您不能將一個變量與多個值進行比較。 你的代碼應該是這樣的:
if (location == 1 || location == 2 || location == 3) { /* some code */ }
但是因為您使用的是特定范圍內的數字,所以使用時間較短
if (location > 0 && location < 4) { /* some code */ }
您還可以編寫一個函數來比較多個值:
bool Compare(object variable, params object[] values) {
foreach (object value in values) if (!(variable == value)) return false;
return true;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.