Descarga la aplicación para disfrutar aún más
Vista previa del material en texto
Ejercicio: Elabora una calculadora completa en el lenguaje C++ Solución: #include <iostream> #include <string> #include <stack> #include <cmath> // Función para evaluar una expresión matemática double evaluateExpression(const std::string& expression) { std::stack<double> numbers; std::stack<char> operators; for (char c : expression) { if (isspace(c)) { continue; } else if (isdigit(c)) { std::string numberStr; numberStr += c; while (isdigit(expression[++i])) { numberStr += expression[i]; } numbers.push(std::stod(numberStr)); } else if (c == '(') { operators.push(c); } else if (c == ')') { while (operators.top() != '(') { double operand2 = numbers.top(); numbers.pop(); double operand1 = numbers.top(); numbers.pop(); char op = operators.top(); operators.pop(); if (op == '+') { numbers.push(operand1 + operand2); } else if (op == '-') { numbers.push(operand1 - operand2); } else if (op == '*') { numbers.push(operand1 * operand2); } else if (op == '/') { numbers.push(operand1 / operand2); } else if (op == '^') { numbers.push(pow(operand1, operand2)); } } operators.pop(); } else { while (!operators.empty() && operators.top() != '(' && (precedence(c) <= precedence(operators.top()))) { double operand2 = numbers.top(); numbers.pop(); double operand1 = numbers.top(); numbers.pop(); char op = operators.top(); operators.pop(); if (op == '+') { numbers.push(operand1 + operand2); } else if (op == '-') { numbers.push(operand1 - operand2); } else if (op == '*') { numbers.push(operand1 * operand2); } else if (op == '/') { numbers.push(operand1 / operand2); } else if (op == '^') { numbers.push(pow(operand1, operand2)); } } operators.push(c); } } while (!operators.empty()) { double operand2 = numbers.top(); numbers.pop(); double operand1 = numbers.top(); numbers.pop(); char op = operators.top(); operators.pop(); if (op == '+') { numbers.push(operand1 + operand2); } else if (op == '-') { numbers.push(operand1 - operand2); } else if (op == '*') { numbers.push(operand1 * operand2); } else if (op == '/') { numbers.push(operand1 / operand2); } else if (op == '^') { numbers.push(pow(operand1, operand2)); } } return numbers.top(); } int main() { std::string expression; std::cout << "Ingrese una expresión matemática: "; std::getline(std::cin, expression); double result = evaluateExpression(expression); std::cout << "El resultado es: " << result << std::endl; return 0; }
Compartir