Как включить цикл, чтобы позволить пользователю продолжать использовать калькулятор JavaScript, пока он не решит выйти?Javascript

Форум по Javascript
Anonymous
Как включить цикл, чтобы позволить пользователю продолжать использовать калькулятор JavaScript, пока он не решит выйти?

Сообщение Anonymous »

Я создал простой калькулятор JavaScript, используя библиотеку readline-sync для node.js для обработки ввода/вывода терминала. Калькулятор спрашивает пользователя, какую операцию он хотел бы выполнить (+, -, *, /). После того, как они выбрали операцию, она запрашивает два числа. Он выполняет расчет и отображает результат, например, 45+9 = 54. После того, как он отображает результат, он должен спросить, хочет ли пользователь выполнить другой расчет. Как добавить цикл, чтобы позволить пользователю продолжать использовать калькулятор, пока он не решит выйти?const calculator = require('readline-sync');

let operations = ['+', '-', '*', '/'];
let index = null;
let operator = null;
let firstNumber = 0;
let secondNumber = 0;

// Gets the operation question and the options
function operationQuestion(){
operator = calculator.question("What operation would you like to perform?"
+'\nOptions:'
+'\nAddition ('+ operations[0]+')'
+'\nSubtraction ('+ operations[1]+')'
+'\nMultiplication ('+ operations[2]+')'
+'\nDivision ('+ operations[3]+')\n'
);

if (!operations.includes(operator)) {
console.log("That is not a valid operation");
operationQuestion();
}

// Gets the first and second number
firstNumber = calculator.questionInt("Type the first number: ");
secondNumber = calculator.questionInt("Type the second number: ");

// 4 of the operations
switch(operator) {
case '+':
console.log("The result of "+firstNumber + operator +secondNumber+" = "+ (firstNumber + secondNumber));
break;
case '-':
console.log("The result of "+firstNumber + operator +secondNumber+" = "+ (firstNumber - secondNumber));
break;
case '*':
console.log("The result of "+firstNumber + operator +secondNumber+" = "+ (firstNumber * secondNumber));
break;
case '/':
console.log("The result of "+firstNumber + operator +secondNumber+" = "+ (firstNumber / secondNumber));
break;
default:
console.log("Something went wrong :(");
}
}

// Logic
operationQuestion();

input = calculator.question("Do you want to perform another calculation?")


Подробнее здесь: https://stackoverflow.com/questions/795 ... -calculato

Вернуться в «Javascript»