2012-12-25 26 views
1

我的C#代碼的操作數:不能被應用於類型「INT」和「INT」」

public int printallancestor(Node root, Node key) 
{ 
    if(root == null) 
      return 0; 
    if(root == key) 
      return 1; 
    if(printallancestor(root.leftChild,key)||printallancestor(root.rightChild,key)) 
    { 
      Console.WriteLine(root.iData); 
      return 1; 
    } 
    return 0; 
} 

從上面的代碼我得到以下錯誤下面的行if(printallancestor(root.leftChild,key)||printallancestor(root.rightChild,key))不能被應用於類型的操作數「詮釋'和‘廉政’什麼不對這個

回答

3

它看起來像你的方法:?

printallancestor(root.leftChild,key) 

返回一個整數值,而你試圖在一個條件下使用它。您只能使用狀況布爾型像你現在這樣

我相信你期待你的方法分別返回10真假,你不能做你現在正在做的在C#什麼。您可以嘗試:

if(printallancestor(root.leftChild,key) == 1|| .... 

或者,如果你期待值大於1爲真,則:

if(printallancestor(root.leftChild,key) > 1) // true 

您可能會看到:
|| Operator (C# Reference)

的條件或運算符(||)執行邏輯OR 其bool 操作數。如果第一個操作數的計算結果爲真,則不計算第二個操作數 。如果第一個操作數的計算結果爲false,則第二個運算符會確定整個OR表達式是否爲 true或false。

0

printallancestor的返回類型是int。 您正在使用||這是布爾運算符。 嘗試

if(printallancestor(root.leftChild,key) != 0||printallancestor(root.rightChild,key) != 0)

應該解決的問題。

0

運算符OR(||)需要兩個bool操作數,而不是int。

0

您的方法返回int,但您嘗試在if條件中使用。這不好。您只能使用條件bool類型。

試試吧,

if(printallancestor(root.leftChild,key) == 1|| .. 

的條件或運算符(||)執行邏輯或布爾其的 操作數。

0

做到這一點

public bool printallancestor(Node root, Node key) 
    { 
     if(root == null) 
      return false; 
     if(root == key) 
      return true; 
     if(printallancestor(root.leftChild,key)||printallancestor(root.rightChild,key)) 

     { 
      Console.WriteLine(root.iData); 
      return true; 
     } 
     return false; 
    } 
相關問題