2014-10-05 20 views
-2

我試圖做一個隨機數發生器,然後根據隨機數選擇三個選項之一。我想用> X <三的第二選擇,但它給了我一個錯誤:如何將一個> x <在C#

操作「>」不能應用於類型「布爾」和「廉政」

這裏的操作數是代碼:

 int rand; 
     Random myRandom = new Random(); 
     rand = myRandom.Next(0, 90); 

     if (rand < 33) 
     { 

     } 

     if (33 > rand < 66) 
     { 

     } 

     if (rand > 66) 
     { 

     } 
+0

你甚至指的是什麼?沒有任何意義... – 2014-10-05 16:00:41

+0

你甚至不需要和。如果rand <33 else,如果rand <67,否則如果rand> 66,你會得到相同的結果,但如果運行整個if塊,它將運行少一個操作。 – deathismyfriend 2014-10-05 16:12:31

回答

2

你應該使用和&&運營商在

if (rand > 33 && rand < 66) 
{ 

} 

這可以確保蘭特是less thanANDgreater那麼值指定

+0

謝謝,你解決了我的問題 – Lamprey 2014-10-05 16:00:18

+0

歡迎您,如果它解決了您的問題,請將答案標記爲已接受 – Kypros 2014-10-05 16:01:54

+0

您還應該考慮處理極限值(在本例中爲33和66)。 – 2014-10-05 16:05:04

3

那麼最簡單的選擇是使用else if所以你只需要反正檢查一個條件 - 這意味着它會處理33以及(目前沒有處理):

if (rand < 33) 
{ 
    Console.WriteLine("rand was in the range [0, 32]"); 
} 
else if (rand < 66) 
{ 
    Console.WriteLine("rand was in the range [33, 65]"); 
} 
else 
{ 
    Console.WriteLine("rand was in the range [66, 89]"); 
} 

如果你需要測試兩個條件,但是,你只是想&&檢查他們都是真實的:

// I've deliberately made this >= rather than 33. If you really don't want to do 
// anything for 33, it would be worth making that clear. 
if (rand >= 33 && rand < 66) 

如果翅片d自己這個做了很多,你可能希望有一個擴展方法,所以你可以說:

if (rand.IsInRange(33, 66)) 

其中IsInRange也只是:

public static bool IsInRange(this int value, int minInclusive, int maxExclusive) 
{ 
    return value >= minInclusive && value < maxExclusive; 
} 
0

要檢查你所需要的值的兩個邊界兩個比較。

你可能想使用<=操盤<在比較,否則代碼將爲值3366無可奈何:

if (rand < 33) 
    { 

    } 

    if (33 <= rand && rand < 66) 
    { 

    } 

    if (rand >= 66) 
    { 

    } 

您還可以使用else擺脫一些比較:

if (rand < 33) 
    { 

    } 
    else if (rand < 66) 
    { 

    } 
    else 
    { 

    } 

注意:您有089之間的隨機值,所以如果你希望每個if聲明將用於三分之一的情況下,您將使用值3060而不是3366

相關問題