Grupo
Funciones en C++
Ojetivo
1. Solicitar al usuario que introduzca dos valores enteros.
2. Definir una función que tome dos enteros como parámetros y devuelva el mayor.
3. Llamar a la función con la entrada del usuario y mostrar el resultado.
4. Usar sentencias condicionales dentro de la función para determinar cuál número es mayor.
Escribir una función que calcule el máximo entre dos 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 find the maximum between two numbers
int findMaximum(int a, int b) {
// Use a conditional statement to compare the two numbers
if (a > b) {
return a; // If 'a' is greater, return 'a'
} else {
return b; // Otherwise, return 'b'
}
}
// Main function - starting point of the program
int main() {
int num1, num2; // Variables to store user input
// Prompt the user to enter the first number
cout << "Enter the first number: ";
cin >> num1; // Read the first number
// Prompt the user to enter the second number
cout << "Enter the second number: ";
cin >> num2; // Read the second number
// Call the findMaximum function and store the result
int max = findMaximum(num1, num2);
// Display the maximum of the two numbers
cout << "The maximum of the two numbers is: " << max << endl;
return 0; // End of the program
}
Salida
Enter the first number: 42
Enter the second number: 17
The maximum of the two numbers is: 42
Enter the first number: 5
Enter the second number: 11
The maximum of the two numbers is: 11
Comparte este ejercicio C++