简体   繁体   中英

How can I make my program select numbers that divide the sum of numbers from an array?

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() ?)

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM