2012-11-29 63 views
1

我使用這個代碼顯示的結果爲偶數或奇數,而不是真假這裏預期:三元操作符不工作

Console.WriteLine(" is " + result == true ? "even" : "odd"); 

因此我使用三元運算符,但它拋出的錯誤,一些語法問題在這裏,但我無法捕捉它。 由於提前

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 

    namespace ConsoleApplicationForTesting 
    { 
     delegate int Increment(int val); 
     delegate bool IsEven(int v); 

class lambdaExpressions 
    { 
     static void Main(string[] args) 
     { 

      Increment Incr = count => count + 1; 

      IsEven isEven = n => n % 2 == 0; 


      Console.WriteLine("Use incr lambda expression:"); 
      int x = -10; 
      while (x <= 0) 
      { 
       Console.Write(x + " "); 
       bool result = isEven(x); 
       Console.WriteLine(" is " + result == true ? "even" : "odd"); 
       x = Incr(x); 
      } 
+0

因爲在函數中沒有返回。你期望從IsEven返回布爾(只是猜測)。 Easiset解決方案,只需在Visual Studio中雙擊該行,它就會帶您進入發生錯誤的**精確行**。 – Tigran

+0

而錯誤信息並沒有幫助你? – leppie

+0

@leppie,錯誤是「」運算符'=='不能應用於'string'和'bool'類型的操作數\t「」 –

回答

3

試試:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 

namespace ConsoleApplicationForTesting 
{ 
    delegate int Increment(int val); 
    delegate bool IsEven(int v); 

class lambdaExpressions 
{ 
    static void Main(string[] args) 
    { 

     Increment Incr = count => count + 1; 

     IsEven isEven = n => n % 2 == 0; 


     Console.WriteLine("Use incr lambda expression:"); 
     int x = -10; 
     while (x <= 0) 
     { 
      Console.Write(x + " "); 
      bool result = isEven(x); 
      Console.WriteLine(" is " + (result == true ? "even" : "odd")); 
      x = Incr(x); 
     } 
1

你錯過了一個括號:

Console.WriteLine(" is " + (result == true ? "even" : "odd")); 

編譯器可能會抱怨,你不能添加一個字符串和一個布爾值。通過添加括號將表達式屬性分組,編譯器很高興。你也是。

4

你需要括號。 " is " + (result ? "even" : "odd");

三元運算符有一個較低的優先權,然後concententation(請參閱precendence table at MSDN)。

你原來的代碼說聯合,然後比較true

4

運算符+的優先級高於==。爲了解決這個問題,簡單地把括號圍繞三元expresion:

Console.WriteLine(" is " + (result == true ? "even" : "odd")); 
2
Console.WriteLine(" is {0}", result ? "even" : "odd"); 
+0

+1好,簡單而簡單:) – V4Vendetta

3

這是因爲operator precedence。你表達

" is " + result == true ? "even" : "odd" 

被解釋爲

(" is " + result) == true ? "even" : "odd" 

因爲+==更高的優先級。使用括號或單獨的變量來避免此行爲。

" is " + (result == true ? "even" : "odd") 

var evenOrOdd = result == true ? "even" : "odd"; 
... " is " + evenOrOdd ... 
6

看看你所得到的錯誤:

操作 '==' 不能應用於類型 '字符串' 的操作數和 '布爾'

這是因爲缺少括號。它串聯字符串和布爾值,這會產生一個字符串值,並且您無法將其與bool進行比較。

要解決它:

Console.WriteLine(" is " + (result == true ? "even" : "odd")); 

進一步澄清。

bool result = true; 
string strTemp = " is " + result; 

上述聲明是在一個字符串,is True一個有效的聲明和結果,所以你的說法目前看起來像:

Console.WriteLine(" is True" == true ? "even" : "odd"); 

字符串和布爾之間的上述比較是無效的,因此你錯誤。