如何在部分初始化的数组中访问非0的元素?

时间:2014-07-29 22:53:23

标签: c# arrays

我想将用户为数组输入的所有值相乘。问题是如果使用的数组元素少于50个,结果始终为0.有没有办法只访问用户输入的元素?

static void Main(string[] args)
    {
        const int SIZE = 50;
        int[] array = new int[SIZE];
        int index = 0;
        int aScore = 0;

        do
        {
            Console.WriteLine("Enter a value for the array for position {0} (or 0 to stop):", (index + 1));
            aScore = int.Parse(Console.ReadLine());
            if(aScore >= 0)
            {
                array[index++] = aScore;
            }
        }while (aScore != 0 && index < SIZE);


        Console.WriteLine("The product of the array is: {0}", SumArray(array));
        Console.ReadLine();
    }

    static int SumArray(int[] array)
    {
        int product = 1;
        for (int i = 0; i < array.Length; i++)
        {
            product *= array[i];
        }
        return product;
    }

5 个答案:

答案 0 :(得分:2)

var values = array.Where(x => x != 0).ToArray();

确保您拥有using System.Linq;

正如Tim所说,使用List<int>将是解决此问题的首选方法。 如果您使用List<int>,则可以像这样使用LINQ Aggregate函数

var ints = new List<int> {1, 2, 3, 4, 5};
var product = ints.Aggregate((total, nextNum) => total * nextNum); // product = 120

修改

以下是我如何做的完整示例

private static void Main()
{
    const int maxScores = 50;
    int index = 0;
    int nextScore = 0;
    var scores = new List<int>();

    do
    {
        Console.WriteLine("Enter a value for the array for position {0} (or 0 to stop):", ++index);
        nextScore = int.Parse(Console.ReadLine());
        if (nextScore > 0)
            scores.Add(nextScore);
    } while (nextScore != 0 && index < maxScores);

    Console.WriteLine("The product of the scores is : {0}",
        scores.Aggregate((total, next) => total * next));
    Console.ReadLine();
} 

答案 1 :(得分:0)

在乘以之前检查0:

 if (array[i] != 0)
       product *= array[i]

另外,如果你想要总结&#39;数组,操作应为+=

答案 2 :(得分:0)

你的方法

static int SumArray(int[] array)
    {
        int product = 1;
        for (int i = 0; i < array.Length; i++)
        {
            product *= array[i];
        }
        return product;
    }

应该看起来像这样

static int SumArray(int[] array)
    {
        int product = 1;
        for (int i = 0; i < array.Length; i++)
        {
            if (array[i] != 0)
            {
                 product *= array[i];
            }
        }
        return product;
    }

以及

do
        {
            Console.WriteLine("Enter a value for the array for position {0} (or 0 to stop):", (index + 1));
            aScore = int.Parse(Console.ReadLine());
            if(aScore >= 0)
            {
                array[index++] = aScore;
            }
        }while (aScore != 0 && index < SIZE);

这部分不是实现目标的好方法,因为你也把数值为0的记录放在数组中。你可以用

替换它
  

if(aScore&gt; 0)

如果你愿意,但我建议你使用List而不是数组,并且你不会遇到其他不必要元素的问题。

答案 3 :(得分:0)

您可以完全免除SumArray()方法,只需说:

int product = array
              .Where( n => n != 0 )
              .Aggregate( 1 , (m,n) => m*n )
              ;
Console.WriteLine( "The product of the array is: {0}" ,
   ) ;

你可以使用List<int>(它实际上只是一个可调整长度的数组)并且不用担心它:

static void Main( string[] args )
{
  List<int> scores = new List<int>() ;

  while ( true )
  {
    Console.WriteLine( "Enter a value for the array for position {0} (or 0 to stop):" ,
      1+scores.Count
      ) ;
    int score = int.Parse( Console.ReadLine() ) ;

    if ( score == 0 ) break ;

    values.Add(score);

  }

  int product = scores.Aggregate( 1 , (m,n) => m*n ) ;
  Console.WriteLine( "The product of the array is: {0}" , product ) ;

  return ;
}

或者你可以完全免除维护系列,只需随时随地进行操作:

static void Main( string[] args )
{
  int sum     = 0 ;
  int n       = 0 ;
  int product = 1 ;

  while ( true )
  {
    Console.WriteLine( "Enter a value for the array for position {0} (or 0 to stop):" ,
      1+scores.Count
      ) ;
    int score = int.Parse( Console.ReadLine() ) ;

    if ( score == 0 ) break ;

    sum     += score ;
    product *= score ;
    n++ ;

  }

  Console.WriteLine( "The product of the array is: {0}" , product ) ;
  Console.WriteLine( "The sum of {0} scores is {1}" , n , sum ) ;
  Console.WriteLine( "The mean score is {0}" , (double)sum/(double)n ) ;

  return ;
}

答案 4 :(得分:0)

如果在for循环中测试if (array[i] > 0),则可以多次进行此测试。例如,如果您通知三个数字,那么共同测试将被测试47次。

所以,如果你发现零,最好打破循环。

<!-- language: lang-cs -->

static int SumArray(int[] array)
{
    int product = 1;
    for (int i = 0; i < array.Length; i++)
    {
        if (array[i] == 0) break;
        product *= array[i];
    }
    return product;
}