如何让我的程序选择除数组之和的数字?

时间:2021-08-28 10:36:00

I want my program to read user input and save it into an array, and then sum all the numbers entered by user, and select those, which divide the sum. Is that possible to use any of the ready c# methods to do it (like FindAll() ?)

我希望我的程序读取用户输入并将其保存到数组中,然后对用户输入的所有数字求和,并选择那些除以总和的数字。是否可以使用任何现成的c#方法(如FindAll()?)

Final version of my program should list all numbers that divide the sum of all entered numbers.

我的程序的最终版本应列出所有数字,它们除以所有输入数字的总和。

My code is following :

我的代码如下:

Console.WriteLine ("Please type 10 numbers");

        int[] numbers = new int[10];
        int sum = 0;

        for (int i = 0; i < numbers.Length; i++) {

            string input = Console.ReadLine ();
            int.TryParse (input, out numbers[i]);

            sum += numbers [i];
        }

        Console.WriteLine (sum);

2 个解决方案

#1


1  

Nothing built in, but you can do it like this:

没有内置,但你可以这样做:

int[] data = new [] {2, 3, 4, 5, 6};

int sum = data.Sum();

var dividers = from number in data
               where (sum % number) == 0
               select number;

foreach (var divider in dividers)
    Console.WriteLine(divider);

#2


1  

If you can use LINQ you can do something like:

如果您可以使用LINQ,您可以执行以下操作:

int[] dividers = numbers.Where(number => number % sum == 0).ToArray();

#1


1  

Nothing built in, but you can do it like this:

没有内置,但你可以这样做:

int[] data = new [] {2, 3, 4, 5, 6};

int sum = data.Sum();

var dividers = from number in data
               where (sum % number) == 0
               select number;

foreach (var divider in dividers)
    Console.WriteLine(divider);

#2


1  

If you can use LINQ you can do something like:

如果您可以使用LINQ,您可以执行以下操作:

int[] dividers = numbers.Where(number => number % sum == 0).ToArray();