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

本文关键字:元素 数组 初始化 何访问 访问 | 更新日期: 2023-09-27 18:15:44

我想将用户为数组输入的所有值相乘。问题是,如果使用的数组元素少于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;
    }

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

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

确保你有using System.Linq;

正如Tim上面所说的,使用List<int>将是解决这个问题的首选方法。如果使用List<int>,则可以使用LINQ聚合函数,如下所示

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();
} 

乘前检查是否为0:

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

如果您想要"求和"数组,操作应该是+=

你的方法

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(score> 0)

,但我建议您使用List而不是数组,这样您就不会遇到额外的不必要元素的问题。

你可以完全省略你的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 ;
}

如果在for循环中测试if (array[i] > 0),则可以进行多次测试。例如,输入三个数字,则该条件将测试47次。

所以,如果你发现一个0,最好打破循环。

<!-- 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;
}