那麼最簡單的選擇是使用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;
}
你甚至指的是什麼?沒有任何意義... – 2014-10-05 16:00:41
你甚至不需要和。如果rand <33 else,如果rand <67,否則如果rand> 66,你會得到相同的結果,但如果運行整個if塊,它將運行少一個操作。 – deathismyfriend 2014-10-05 16:12:31