如何在C#中检测数组中的元素何时为空?(当为空时,元素= 0)

par*_*995 4 c# arrays computer-science elements

我有一个5个整数的数组,从1到5.我的赋值告诉我,我需要能够检测数组中至少有一个元素是否大于零.只有当所有元素都为空时,我才会说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;
}
Run Code Online (Sandbox Code Playgroud)

Qua*_*yst 6

您的代码不起作用,因为它只考虑循环中元素中的最后一个元素.试试这个:一旦找到非空元素,返回数组不为空; 否则,返回所有元素都为空:

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;
}
Run Code Online (Sandbox Code Playgroud)

  • 这可能是教授所得到的 - 快速退出方法的执行.每个开发人员应该学习的技术.和那些SESE混蛋一起*地狱*. (4认同)