【问题标题】:c# Print rows from array that only contain positive integersc#从数组中打印仅包含正整数的行
【发布时间】:2014-03-31 23:10:42
【问题描述】:

我真的很接近,但我似乎无法理解最后一步。 所以我想要的是拥有二维矩阵并只打印具有所有正整数的行。

现在我的代码只是取出 0 或负数的整数,但如果该行包含 0 或负数,我需要删除整行。

这就是我现在得到的

输入:

1 2 6 4

1 5 0 9

输出:

1 2 6 4

1 5 

所以基本上它不应该打印第二行 b/c 它有一个非正整数

我做错了什么?

感谢您抽出时间来看看这个!

 static void Main(string[] args)
        {
// reads in multiples lines( array from console)            
List<string> L = readAllLines();

            // feeds read lines into matrix
            int[,] m = convertListToIntMatrix(L);// feeds read lines into matrix

            int Rows = m.GetLength(0);
            int Cols = m.GetLength(1);

            for (int r = 0; r < Rows; r++)
            {
                for (int c = 0; c < Cols; c++)
                {

                    if (m[r, c] <= 0)
                    {

                        break;

                    }
                    else Console.Write("{0} ", m[r, c]);
                }
                Console.WriteLine();

            }

【问题讨论】:

    标签: c# arrays for-loop console


    【解决方案1】:

    把你的循环改成这样:

    for (int r = 0; r < Rows; r++)
    {
        bool rowOkay = true;
        for (int c = 0; c < Cols; c++)
        {
            if (m[r, c] <= 0)
            {
                rowOkay = false;
            }
        }
        if (rowOkay)
        {
            for(int i=0;i<Cols;++i) {Console.Write("{0} ", m[r,i]);}
            Console.WriteLine();
        }
    }
    

    【讨论】:

      【解决方案2】:

      当你找到 0 时你会中断,但你之前输出了所有内容。相反,您可以设置一个标志,然后在未设置标志时对其进行评估以输出该行。您仍然会中断,但会推迟所有输出,直到您知道该行是好的。

      【讨论】:

        【解决方案3】:

        你是吉姆哈里斯的 PP2 班吗?您还可以设置一个变量来计算行中有多少个正数,如果它等于行中的数字或整数,则打印该行。

        【讨论】:

          【解决方案4】:

          如果您使用列表集合,只需检查列表的 Min() 值;

          list1.Min() <= 0
          

          【讨论】:

            猜你喜欢
            • 2019-02-09
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-06-18
            • 2019-03-29
            • 2017-03-24
            • 2017-12-04
            • 2011-02-09
            相关资源
            最近更新 更多