[英]How do I detect when an element in an array is empty in C#? (When empty, element = 0)
我有一個5個整數的數組,從1到5.我的賦值告訴我,我需要能夠檢測數組中至少有一個元素是否大於零。 只有當ALL元素為空時,我才會說var isEmpty為true,然后返回該值。
碼:
public static bool is_empty(int[] S, int n)
{
bool isEmpty = false;
for (int i = 0; i < n; i++)
{
if (S[i] != 0)
{
isEmpty = false;
}
else
{
isEmpty = true;
}
}
return isEmpty;
}
您的代碼不起作用,因為它只考慮循環中元素中的最后一個元素。 試試這個:一旦找到非空元素,返回數組不為空; 否則,返回所有元素都為空:
public static bool is_empty(int[] S, int n)
{
for (int i = 0; i < n; i++)
{
if (S[i] > 0) // negative values still count towards "being empty"
return false;
}
return true;
}
我不確定為什么你有輸入參數n。 所以我刪除了它。 相反,我使用foreach循環遍歷數組中的每個元素。
static bool IsEmpty(int[] S)
{
foreach (int x in S)
{
if (x != 0)
{
return false; //If any element is not zero just return false now
}
}
return true; //If we reach this far then the array isEmpty
}
我認為you don't need variables
你的老師意味着你不需要bool isEmpty
,你可以像其他人一樣使用LINQ,但我懷疑你知道那是什么。
根據您的要求,您可以說“如果我遇到任何非零值,我將獲得返回響應所需的所有信息”。 如果我檢查所有值,並且沒有找到任何非零,我也知道如何回應。 所以嘗試:
for (int i = 0; i < n; i++)
{
if (S[i] != 0)
{
return false;
}
}
return true;
嘗試這個
bool isEmpty = false;
int count = 0;
for(int i=0;i<n;i++){
if(S[i] == 0){
count++;
}
}
isEmpty = (count==n);
你能試一下嗎
S.Any(x => x != 0);
如果數組中的任何元素不等於0,則應該給出true。
同樣,如果需要檢查數組的所有元素,可以瀏覽All選項。
S.All(x => x == 0);
所以你的代碼將是
public static bool is_empty(int[] S)
{
// return true if no element is 0
return !S.Any(x => x != 0);
// or use
return S.All(x => x == 0);
}
更好的是你也不需要創建這個方法,因為你可以直接從你調用這個方法的地方調用這個語句(除非從多個地方調用它)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.