Grupo
Control de Flujo en C++
Ojetivo
1. Pida al usuario que introduzca dos números.
2. Pida al usuario que seleccione una operación (suma, resta, multiplicación o división).
3. Utilice una sentencia switch para gestionar las operaciones y realizar el cálculo correspondiente.
4. Muestre el resultado de la operación seleccionada.
5. Asegúrese de gestionar los errores de división por cero.
Escriba un programa que simule una calculadora con operaciones como suma, resta, multiplicación y división.
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
// Main function - the entry point of the program
int main() {
double num1, num2; // Variables to store the two numbers
char operation; // Variable to store the selected operation
// Ask the user for input
cout << "Enter first number: ";
cin >> num1; // Read the first number
cout << "Enter second number: ";
cin >> num2; // Read the second number
// Ask the user to choose an operation
cout << "Enter operation (+, -, *, /): ";
cin >> operation; // Read the chosen operation
// Switch statement to handle different operations
switch (operation) {
case '+':
cout << "Result: " << num1 + num2 << endl; // Addition
break;
case '-':
cout << "Result: " << num1 - num2 << endl; // Subtraction
break;
case '*':
cout << "Result: " << num1 * num2 << endl; // Multiplication
break;
case '/':
// Check if division by zero is attempted
if (num2 != 0) {
cout << "Result: " << num1 / num2 << endl; // Division
} else {
cout << "Error: Division by zero is not allowed." << endl; // Handle division by zero
}
break;
default:
cout << "Invalid operation." << endl; // Handle invalid operation input
}
return 0; // Return 0 to indicate that the program executed successfully
}
Salida
Enter first number: 10
Enter second number: 5
Enter operation (+, -, *, /): +
Result: 15
//Or if you try division by zero:
Enter first number: 10
Enter second number: 0
Enter operation (+, -, *, /): /
Error: Division by zero is not allowed.
Comparte este ejercicio C++