Encuentra El Valor Máximo En Una Matriz De Números Reales En C#

Este programa en C# demuestra cómo escribir una función que recibe un array de números reales como parámetro y devuelve el mayor valor de dicho array. La función itera sobre todos los elementos del array y los compara para encontrar el mayor. Este tipo de función es útil al trabajar con arrays de datos numéricos y al buscar el mayor valor de forma eficiente.

Grupo

Funciones en C#

Objectivo

1. Cree una función llamada "Máximo" que acepte un array de coma flotante como parámetro.
2. Recorra el array para comparar cada elemento con el máximo actual.
3. Devuelva el valor más alto del array.
4. Pruebe la función con un array de números reales, como {1.5f, 0.7f, 8.0f}.
5. Muestre el resultado en la consola.

Escriba una función de C# que devuelva el mayor valor almacenado en un array de números reales especificado como parámetro.

Ejemplo de ejercicio en C#

 Copiar código C#
using System;

class Program
{
    // Function to find the maximum value in an array of floats
    public static float Maximum(float[] data)
    {
        // Initialize the max value to the first element in the array
        float max = data[0];

        // Iterate through the array and compare each element with max
        for (int i = 1; i < data.Length; i++)
        {
            // If the current element is greater than the max, update max
            if (data[i] > max)
            {
                max = data[i];
            }
        }

        // Return the largest value found
        return max;
    }

    // Main method to test the Maximum function
    public static void Main()
    {
        // Define an array of real numbers
        float[] data = {1.5f, 0.7f, 8.0f};

        // Call the Maximum function and store the result
        float max = Maximum(data);

        // Display the result
        Console.WriteLine("The maximum value is: " + max);
    }
}

 Output

The maximum value is: 8

Comparte este ejercicio de C#