Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const readline = require('readline');
- const rl = readline.createInterface({
- input: process.stdin,
- output: process.stdout
- });
- function calculator() {
- rl.question('Enter the first number: ', (num1) => {
- rl.question('Enter the second number: ', (num2) => {
- rl.question('Choose an operation (+, -, *, /): ', (operator) => {
- let result;
- switch(operator) {
- case '+':
- result = parseFloat(num1) + parseFloat(num2);
- break;
- case '-':
- result = parseFloat(num1) - parseFloat(num2);
- break;
- case '*':
- result = parseFloat(num1) * parseFloat(num2);
- break;
- case '/':
- result = parseFloat(num1) / parseFloat(num2);
- break;
- default:
- console.log('Invalid operator.');
- calculator();
- return;
- }
- console.log(`Result: ${result}`);
- rl.question('Do you want to continue? (y/n): ', (answer) => {
- if (answer.toLowerCase() === 'y') {
- calculator();
- } else {
- rl.close();
- }
- });
- });
- });
- });
- }
- calculator();
- /*
- README FIRST!!
- In this code, we create a readline interface to get input from the user on the terminal. Then, we define a calculator function that prompts the user for the first and second numbers and the operation they want to perform. Based on the operator, we perform the calculation and print the result to the console. We then ask the user if they want to continue using the app or exit.
- If the user chooses to continue, we call the calculator function again. If they choose to exit, we close the readline interface and the app terminates.
- Note that we use parseFloat to convert the user input to numbers, and we handle invalid operator inputs by printing an error message and calling the calculator function again.
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement