-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimpleCalculator.js
More file actions
78 lines (68 loc) · 2.21 KB
/
simpleCalculator.js
File metadata and controls
78 lines (68 loc) · 2.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
// Function to perform the calculation
function calculate(num1, num2, operation) {
switch (operation) {
case 'add':
return num1 + num2;
case 'subtract':
return num1 - num2;
case 'multiply':
return num1 * num2;
case 'divide':
if (num2 === 0) return 'Cannot divide by zero';
return num1 / num2;
default:
return 'Invalid operation';
}
}
// Function to get user input and display the result
function handleUserInput() {
// Get the first number from the user
const num1 = parseFloat(prompt('Enter the first number:'));
// Get the second number from the user
const num2 = parseFloat(prompt('Enter the second number:'));
// Get the operation from the user
const operation = prompt('Enter the operation (add, subtract, multiply, divide):').toLowerCase();
// Validate the inputs and calculate the result
if (!isNaN(num1) && !isNaN(num2)) {
const result = calculate(num1, num2, operation);
alert(`Result: ${result}`);
} else {
alert('Invalid input. Please enter valid numbers.');
}
}
// Call the function to handle user input
handleUserInput();
// Function to perform the calculation
function calculate(num1, num2, operation) {
switch (operation) {
case 'add':
return num1 + num2;
case 'subtract':
return num1 - num2;
case 'multiply':
return num1 * num2;
case 'divide':
if (num2 === 0) return 'Cannot divide by zero';
return num1 / num2;
default:
return 'Invalid operation';
}
}
// Function to get user input and display the result
function handleUserInput() {
// Get the first number from the user
const num1 = parseFloat(prompt('Enter the first number:'));
// Get the second number from the user
const num2 = parseFloat(prompt('Enter the second number:'));
// Get the operation from the user
const operation = prompt('Enter the operation (add, subtract, multiply, divide):').toLowerCase();
// Validate the inputs and calculate the result
if (!isNaN(num1) && !isNaN(num2)) {
const result = calculate(num1, num2, operation);
alert(`Result: ${result}`);
} else {
alert('Invalid input. Please enter valid numbers.');
}
}
// Call the function to handle user input
handleUserInput();