Как найти максимальное число си шарп

Another answer in this long list, but I think it’s worth it, because it provides some benefits that most (or all?) other answers don’t:

  1. The method below loops only once through the collection, therefore the order is O(N).
  2. The method finds ALL indices of the maximum values.
  3. The method can be used to find the indices of any comparison: min, max, equals, not equals, etc.
  4. The method can look into objects via a LINQ selector.

Method:

///-------------------------------------------------------------------
/// <summary>
/// Get the indices of all values that meet the condition that is defined by the comparer.
/// </summary>
/// <typeparam name="TSource">The type of the values in the source collection.</typeparam>
/// <typeparam name="TCompare">The type of the values that are compared.</typeparam>
/// <param name="i_collection">The collection of values that is analysed.</param>
/// <param name="i_selector">The selector to retrieve the compare-values from the source-values.</param>
/// <param name="i_comparer">The comparer that is used to compare the values of the collection.</param>
/// <returns>The indices of all values that meet the condition that is defined by the comparer.</returns>
/// Create <see cref="IComparer{T}"/> from comparison function:
///   Comparer{T}.Create ( comparison )
/// Comparison examples:
/// - max:      (a, b) => a.CompareTo (b)
/// - min:      (a, b) => -(a.CompareTo (b))
/// - == x:     (a, b) => a == 4 ? 0 : -1
/// - != x:     (a, b) => a != 4 ? 0 : -1
///-------------------------------------------------------------------
public static IEnumerable<int> GetIndices<TSource, TCompare> (this IEnumerable<TSource> i_collection,
                                                                   Func<TSource, TCompare> i_selector,
                                                                   IComparer<TCompare> i_comparer)
{
  if (i_collection == null)
    throw new ArgumentNullException (nameof (i_collection));
  if (!i_collection.Any ())
    return new int[0];

  int index = 0;
  var indices = new List<int> ();
  TCompare reference = i_selector (i_collection.First ());

  foreach (var value in i_collection)
  {
    var compare = i_selector (value);
    int result = i_comparer.Compare (compare, reference);
    if (result > 0)
    {
      reference = compare;
      indices.Clear ();
      indices.Add (index);
    }
    else if (result == 0)
      indices.Add (index);

    index++;
  }

  return indices;
}

If you don’t need the selector, then change the method to

public static IEnumerable<int> GetIndices<TCompare> (this IEnumerable<TCompare> i_collection,
                                                          IComparer<TCompare> i_comparer)

and remove all occurences of i_selector.

Proof of concept:

//########## test #1: int array ##########
int[] test = { 1, 5, 4, 9, 2, 7, 4, 6, 5, 9, 4 };

// get indices of maximum:
var indices = test.GetIndices (t => t, Comparer<int>.Create ((a, b) => a.CompareTo (b)));
// indices: { 3, 9 }

// get indices of all '4':
indices = test.GetIndices (t => t, Comparer<int>.Create ((a, b) => a == 4 ? 0 : -1));
// indices: { 2, 6, 10 }

// get indices of all except '4':
indices = test.GetIndices (t => t, Comparer<int>.Create ((a, b) => a != 4 ? 0 : -1));
// indices: { 0, 1, 3, 4, 5, 7, 8, 9 }

// get indices of all '15':
indices = test.GetIndices (t => t, Comparer<int>.Create ((a, b) => a == 15 ? 0 : -1));
// indices: { }

//########## test #2: named tuple array ##########
var datas = new (object anything, double score)[]
{
  (999,               0.1),
  (new object (),     0.42),
  ("hello",           0.3),
  (new Exception (),  0.16),
  ("abcde",           0.42)
};
// get indices of highest score:
indices = datas.GetIndices (data => data.score, Comparer<double>.Create ((a, b) => a.CompareTo (b)));
// indices: { 1, 4 }

Enjoy! 🙂

It’s the first time I am using c# so I am not very familiar with it. I would like to create a simple program to find the biggest number if I have the user entering 3 numbers. I just need to know what to put in the code, because I am not very sure.

Draken's user avatar

Draken

3,13413 gold badges33 silver badges53 bronze badges

asked Feb 25, 2011 at 12:33

Oliver's user avatar

2

Use Math.Max:

int x = 3, y = 4, z = 5;
Console.WriteLine(Math.Max(Math.Max(x, y), z));

answered Feb 25, 2011 at 12:35

Fredrik Mörk's user avatar

Fredrik MörkFredrik Mörk

155k29 gold badges290 silver badges343 bronze badges

6

There is the Linq Max() extension method. It’s available for all common number types(int, double, …). And since it works on any class that implements IEnumerable<T> it works on all common containers such as arrays T[], List<T>,…

To use it you need to have using System.Linq in the beginning of your C# file, and need to reference the System.Core assembly. Both are done by default on new projects(C# 3 or later)

int[] numbers=new int[]{1,3,2};
int maximumNumber=numbers.Max();

You can also use Math.Max(a,b) which works only on two numbers. Or write a method yourself. That’s not hard either.

answered Feb 25, 2011 at 12:35

CodesInChaos's user avatar

CodesInChaosCodesInChaos

106k23 gold badges215 silver badges261 bronze badges

3

You can use the Math.Max method to return the maximum of two numbers, e.g. for int:

int maximum = Math.Max(number1, Math.Max(number2, number3))

There ist also the Max() method from LINQ which you can use on any IEnumerable.

answered Feb 25, 2011 at 12:35

Sören's user avatar

SörenSören

2,6512 gold badges19 silver badges22 bronze badges

using System;
using System.Linq;

class Program
{
    static void Main(string[] args)
    {
        int[] numbers = { 3, 9, 5 };
        int biggestNumber = numbers.Max();
        Console.WriteLine(biggestNumber);
        Console.ReadLine();
    }
}

answered Feb 25, 2011 at 12:41

kazim's user avatar

kazimkazim

2,0811 gold badge19 silver badges15 bronze badges

I needed to find a way to do this too, using numbers from different places and not in a collection. I was sure there was a method to do this in c#…though by the looks of it I’m muddling my languages…

Anyway, I ended up writing a couple of generic methods to do it…

    static T Max<T>(params T[] numberItems)
    {
        return numberItems.Max();
    }

    static T Min<T>(params T[] numberItems)
    {
        return numberItems.Min();
    }

…call them this way…

    int intTest = Max(1, 2, 3, 4);
    float floatTest = Min(0f, 255.3f, 12f, -1.2f);

answered Sep 27, 2011 at 9:09

Branasinflake's user avatar

If your numbers are a, b and c then:

    int a = 1;
    int b = 2;
    int c = 3;

    int d =  a > b ? a : b;
    return c > d ? c : d;

This could turn into one of those “how many different ways can we do this” type questions!

answered Feb 25, 2011 at 12:41

Jon Egerton's user avatar

Jon EgertonJon Egerton

40.2k11 gold badges97 silver badges129 bronze badges

1

Here is the simple logic to find Biggest/Largest Number

Input : 11, 33, 1111, 4, 0 Output : 1111

namespace PurushLogics
{
    class Purush_BiggestNumber
    {
        static void Main()
        {
            int count = 0;
            Console.WriteLine("Enter Total Number of Integersn");
            count = int.Parse(Console.ReadLine());

            int[] numbers = new int[count];

            Console.WriteLine("Enter the numbers"); // Input 44, 55, 111, 2 Output = "111"
            for (int temp = 0; temp < count; temp++)
            {
                numbers[temp] = int.Parse(Console.ReadLine());
            }

            int largest = numbers[0];
            for (int big = 1; big < numbers.Length; big++)
            {
                if (largest < numbers[big])
                {
                    largest = numbers[big];
                }
            }
            Console.WriteLine(largest);
            Console.ReadKey();
        }
    }
}

answered Feb 15, 2018 at 7:56

Purushoth's user avatar

В этом посте будет обсуждаться, как найти минимальное и максимальное число из массива в C#.

1. Использование Linq

Простое решение для поиска минимального и максимального значения в последовательности значений — использование Enumerable.Min а также Enumerable.Max методы из System.Linq пространство имен.

using System;

using System.Linq;

public class Example

{

    public static void Main()

    {

        int[] arr = { 8, 3, 5, 1, 2 };

        Console.WriteLine(“Minimum number is “ + arr.Min());

        Console.WriteLine(“Maximum number is “ + arr.Max());

    }

}

Скачать  Выполнить код

результат:

Minimum number is -1
Maximum number is 8

2. Использование Array.Sort() Метод

Другой вероятный, но менее рекомендуемый способ найти минимум/максимум массива — отсортировать массив в порядке возрастания. Тогда первый и последний элементы отсортированного массива будут минимальным и максимальным элементом соответственно.

using System;

public class Example

{

    public static void Main()

    {

        int[] arr = { 8, 3, 5, 1, 2 };

        Array.Sort(arr);

        if (arr.Length > 0) {

            Console.WriteLine(“Minimum number is “ + arr[0]);

            Console.WriteLine(“Maximum number is “ + arr[arr.Length 1]);

        }

    }

}

Скачать  Выполнить код

результат:

Minimum number is -1
Maximum number is 8

3. Использование пользовательской процедуры

Наконец, мы можем написать собственную процедуру для нахождения минимального и максимального числа массива. Идея состоит в том, чтобы пройтись по массиву и отслеживать минимальное или максимальное значение, найденное на данный момент. Вот как будет выглядеть код:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

using System;

public class Example

{

    public static int findMin(int[] arr)

    {

        if (arr.Length == 0) {

            throw new Exception(“Array is empty”);

        }

        int min = int.MaxValue;

        foreach (var i in arr) {

            if (i < min) {

                min= i;

            }

        }

        return min;

    }

    public static int findMax(int[] arr)

    {

        if (arr.Length == 0) {

            throw new Exception(“Array is empty”);

        }

        int max = int.MinValue;

        foreach (var i in arr) {

            if (i > max) {

                max = i;

            }

        }

        return max;

    }

    public static void Main()

    {

        int[] arr = { 8, 3, 5, 1, 2 };

        Console.WriteLine(“Minimum number is “ + findMin(arr));

        Console.WriteLine(“Maximum number is “ + findMax(arr));

    }

}

Скачать  Выполнить код

результат:

Minimum number is -1
Maximum number is 8

Вот и все, что касается нахождения минимального и максимального числа из массива в C#.

Спасибо за чтение.

Пожалуйста, используйте наш онлайн-компилятор размещать код в комментариях, используя C, C++, Java, Python, JavaScript, C#, PHP и многие другие популярные языки программирования.

Как мы? Порекомендуйте нас своим друзьям и помогите нам расти. Удачного кодирования 🙂

2 / 2 / 0

Регистрация: 07.04.2016

Сообщений: 34

1

Найти минимальный и максимальный элемент массива

30.04.2016, 15:28. Показов 59366. Ответов 5


Студворк — интернет-сервис помощи студентам

Как найти максимальный и минимальный элемент ,создав массив чисел. А главное как расписать в си шарпе?



0



Dark Byte

30 / 47 / 19

Регистрация: 23.10.2014

Сообщений: 1,001

30.04.2016, 15:33

2

C#
1
2
3
var a = new[] { 0, 1, 2, 3 };
var min = a.Min();
var max = a.Max();



0



sergeevdokimov

2 / 2 / 0

Регистрация: 07.04.2016

Сообщений: 34

30.04.2016, 16:30

 [ТС]

3

Программа написана, но почему-то не работает правильно. В чём проблема?

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace massiv
{
    class Program
    {
        static void Main(string[] args)
        {
 
            int i, n = 3;
            double[] a = new double[n];
            for (i = 0; i < n; i++)
            {
                Console.Write("Введите элемент массива: ");
                a[i] = Convert.ToDouble(Console.ReadLine());
            }
 
            double min = a[0];
            for (i = 1; i < n; i++)
            {
                if (min > a[i])
                    min = a[i];
            }
            Console.WriteLine("min = {0}", min);
 
            double max = a[0];
            for (i = 1; i < n; i++)
            {
                if (a[i] < 5 && a[i] > max)
                    max = a[i];
            }
            Console.WriteLine("max = {0}", max);
        }
    }
}



1



10 / 10 / 15

Регистрация: 29.11.2015

Сообщений: 43

30.04.2016, 17:23

4

зачем в цикле нахождения max в условии стоит “a[i] < 5” ?



0



2 / 2 / 0

Регистрация: 07.04.2016

Сообщений: 34

30.04.2016, 18:05

 [ТС]

5

даже если поставлю “n” заместь “5”, всё равно не правильно работаёт!



0



Dragon6

5 / 5 / 4

Регистрация: 10.02.2011

Сообщений: 48

01.05.2016, 00:20

6

Там не должно быть такого условия (“a[i] < что-либо”), ведь что делает цикл нахождения max (да и min, в принципе, тоже):
– Такс, предположим, что a[0] (первый элемент массива) – это максимальное число во всем массиве
– Смотрим остальные элементы массива
– Так, этот элемент больше чем наш предпологаемый максимум?
– Если он больше: Ага, он больше – теперь его примем за максимум
– Если не больше: Ну и фиг с ним
Следовательно условие должно быть просто:

C#
1
if( a[i] > max )

ну или:

C#
1
if( max < a[i] )

На личное усмотрение



1



Нахождение максимального элемента массива

Из этой небольшой заметки вы узнаете, как найти максимальный элемент массива с помощью языка c#

Вообще данную задачу можно решить множеством различных способов, так например, для нахождения максимального элемента массива мы можем использовать обычную сортировку, например, воспользуемся статическим методом Sort класса Array:

Код:

int [] ar = {67,34,3,8,35,23};
Array.Sort(ar);
int maxValue = ar[ar.Length-1];
//Результат: 67

Либо та же сортировка, но только в результате максимальный элемент будет самым первым, например:

Код:

int [] ar = { -1, -5, 0, 108, 34, 35, 21 };
int maxValue = ar.OrderByDescending(x => x).First();
//Результат: 108

Также в языке c# существует очень простой и компактный способ, который позволяет быстро найти максимальный элемент в массиве, для этого всего лишь нужно воспользоваться методом расширения Max, например:

Код:

int [] ar = {67,34,3,8,35,23};
int maxValue = ar.Max<int>();
//Результат: 67

Для многомерного массива:

Код:

int [,] numbers = {{270, 3, 62, 91, 2, 178},{22, 32, 65, 69, 8, 6}};
int maxValue = numbers.Cast<int>().Max();
//Результат: 270

Для jagged массива:

Код:

int [][] numbers = { new int [] {177,130,50,7,9},
new int [] {37,41,6,94},
new int [] {112,22,77,55}};
int maxValue = numbers.SelectMany(y => y).Max();
//Результат: 177

Читайте также:

  • Как изменить данные в файле манифест
  • C# Как переименовать файл?
  • Mysql метод ExecuteScalar

Добавить комментарий