Grupo
Funciones en C++
Ojetivo
1. Define una función que acepte dos parámetros de coma flotante: base y altura.
2. Usa la fórmula área = (base × altura) / 2 para calcular el área.
3. Devuelve el resultado de la función.
4. En la función principal, solicita al usuario que introduzca la base y la altura del triángulo.
5. Llama a la función y muestra el área calculada.
Crea una función que calcule el área de un triángulo.
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 area of a triangle
float calculateTriangleArea(float base, float height) {
// Use the formula: (base × height) / 2
return (base * height) / 2;
}
// Main function - entry point of the program
int main() {
float base, height; // Variables to store the base and height
// Ask the user to enter the base of the triangle
cout << "Enter the base of the triangle: ";
cin >> base; // Read the base input
// Ask the user to enter the height of the triangle
cout << "Enter the height of the triangle: ";
cin >> height; // Read the height input
// Call the function to calculate the area
float area = calculateTriangleArea(base, height);
// Display the result
cout << "The area of the triangle is: " << area << endl;
return 0; // End of the program
}
Salida
Enter the base of the triangle: 10
Enter the height of the triangle: 5
The area of the triangle is: 25
Comparte este ejercicio C++