[英]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.