2013-05-09 234 views
5

我有一個數組,說如何檢查數組中的所有元素是否都是正整數?

int[] array = new int[] { 1, 5, 11, 5 }; 

我如何檢查(以最簡便而有效的),所有的元素都是正?如果至少有一個數字不是正整數,系統將以負面方式進行響應。

所需的輸出:

如果所有的數字都是肯定的,那麼它會顯示 「一切積極」 其他 「錯誤」

我的投籃

int[] array = new int[] { 1, 5, 11, 5 }; 
var x = array.All(c => c >= '0' && c <= '9'); 
if (x == true) "Positive" else "Wrong"; 
+2

'array.All(x => x> -1)'? – Patashu 2013-05-09 05:43:02

+0

那麼你應該檢查使用'.Any'是否小於零 – V4Vendetta 2013-05-09 05:44:34

回答

12

你幾乎在那裏 - 但你是比較字符而不是整數。

如果你想檢查是否一切嚴格爲正,用途:

bool allPositive = array.All(x => x > 0); 

如果你確實要檢查他們都是非負(即0是可以接受的)使用方法:

bool allNonNegative = array.All(x => x >= 0); 

你一定要考慮你想用0來做什麼,因爲你的問題陳述實際上是矛盾的。 (「所有積極的」和「沒有消極的」是不一樣的。)

請注意,就像Any,All一知道結果就會退出 - 所以如果第一個值是負值,不需要仔細觀察其餘部分。

+0

該死!我的解決方案比較快':D' – 2013-05-09 05:58:13

5

使用Enumerable.Any像:

if(array.Any(r => r < 0)) 
{ 
    //Negative number found 
} 
else 
{ 
    //All numbers are positive 
} 

或者你可以使用Enumerable.All像:

if(array.All(r => r > 0)) 
{ 
    //All numbers are positive 
} 
else 
{ 
    //Negative number found 
} 
+1

鑑於OP表示這是「所有的值都是正數」,我認爲使用'All'和一個正確的測試比'Any'測試和結果逆轉。 – 2013-05-09 05:46:03

+0

@JonSkeet,謝謝,修改我的回答 – Habib 2013-05-09 05:48:27

+0

OP確實提到'至少有一個負數',所以'Any'仍然有效。 – 2013-05-09 05:49:06

3

你幾乎沒有。但在你的情況下,你比較字符而不是你的情況中錯誤的整數。

使用Enumerable.All like;

確定序列的所有元素是否滿足條件。

int[] array = new int[] { 1, 5, 11, 5 }; 
bool allPositive = array.All(x => x > 0); 
Console.WriteLine(allPositive); 

這裏是一個DEMO

還記得0是不正確的。

1

下面是一個C#解決您的問題(它應該是相當有效的性能明智):

int[] array = new int[] { 1, 5, 11,5 }; 

bool _allPositive=true; 

for (int i=0;i<array.length;i++){ 
if(array[i]<0 {_allPositive=false; break;} 
} 

bool _allPositive表示結果(可以使用字符串變種,如果你喜歡)。從本質上講,相同的語法可以應用於類似Java的語言,包括腳本。

1
string result = array.Any(x => x < 0)?"Wrong":"Positive"; 
相關問題