Grupo
Funciones en C++
Ojetivo
1. Define una función que reciba un array de números y su longitud.
2. Recorre el array para calcular la suma total de los elementos.
3. Divide la suma total entre el número de elementos para obtener el promedio.
4. En la función principal, solicita al usuario el número de elementos y luego introduce cada número en un array.
5. Llama a la función y muestra el resultado promedio.
Escribe una función que calcule el promedio de una lista de números.
Ejemplo de Código C++
Mostrar Código C++
#include <iostream> // Include the iostream library for input and output
using namespace std; // Use the standard namespace
// Function to calculate the average of an array of numbers
float calculateAverage(int numbers[], int size) {
int sum = 0; // Variable to store the total sum
// Loop through each element in the array
for (int i = 0; i < size; i++) {
sum += numbers[i]; // Add each element to the sum
}
// Calculate and return the average
return static_cast<float>(sum) / size;
}
// Main function - entry point of the program
int main() {
int size; // Variable to store the number of elements
// Ask the user for the number of elements
cout << "Enter the number of elements: ";
cin >> size; // Read the size
int numbers[size]; // Declare the array with the given size
// Prompt the user to input the numbers
cout << "Enter " << size << " numbers:" << endl;
for (int i = 0; i < size; i++) {
cin >> numbers[i]; // Read each number
}
// Call the function to calculate the average
float average = calculateAverage(numbers, size);
// Display the calculated average
cout << "The average is: " << average << endl;
return 0; // End of the program
}
Salida
Enter the number of elements: 5
Enter 5 numbers:
10
20
30
40
50
The average is: 30
Comparte este ejercicio C++