Grupo
Programación Orientada a Objetos en C++
Ojetivo
1. Define una clase llamada "Círculo" con el atributo "radio" (double).
2. Agrega un constructor que tome el radio como parámetro.
3. Implementa dos funciones miembro: una para calcular el área y otra para calcular el perímetro.
4. En la función principal, crea un objeto de la clase Círculo con un radio dado y muestra el área y el perímetro.
Desarrolla una clase Círculo que calcule el área y el perímetro de un círculo.
Ejemplo de Código C++
Mostrar Código C++
#include <iostream> // Include the standard input/output library
#include <cmath> // Include the cmath library to use mathematical functions like M_PI
using namespace std;
// Define the 'Circle' class
class Circle {
private:
double radius; // Private attribute for radius
public:
// Constructor to initialize the 'Circle' object with a radius
Circle(double r) {
radius = r; // Set the radius to the passed value
}
// Member function to calculate the area of the circle
double calculateArea() {
return M_PI * radius * radius; // Use the formula πr^2 to calculate the area
}
// Member function to calculate the perimeter (circumference) of the circle
double calculatePerimeter() {
return 2 * M_PI * radius; // Use the formula 2πr to calculate the perimeter
}
};
int main() {
// Create an object of the 'Circle' class with a radius of 5
Circle circle1(5);
// Output the area and perimeter of the circle
cout << "Area of the circle: " << circle1.calculateArea() << endl; // Print area
cout << "Perimeter of the circle: " << circle1.calculatePerimeter() << endl; // Print perimeter
return 0; // Return 0 to indicate successful execution
}
Salida
Area of the circle: 78.5398
Perimeter of the circle: 31.4159
Comparte este ejercicio C++