-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscientificCalculator.java
98 lines (87 loc) · 3.33 KB
/
scientificCalculator.java
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
import java.util.Scanner;
// commit
public class scientificCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
boolean running = true;
System.out.println("Scientific Calculator");
while (running) {
System.out.println("1. Square root function (sqrt)");
System.out.println("2. Factorial function (x!)");
System.out.println("3. Natural logarithm (ln)");
System.out.println("4. Power function (x^y)");
System.out.println("5. Exit");
System.out.print("Enter your choice (1-5): ");
int choice = scanner.nextInt();
double num, result;
switch (choice) {
case 1:
System.out.print("Enter a number to find its square root: ");
num = scanner.nextDouble();
squareRoot(num);
break;
case 2:
System.out.print("Enter a number to find its factorial: ");
num = scanner.nextDouble();
result = factorial((int) num);
System.out.println("Factorial of " + num + " is " + result);
break;
case 3:
System.out.print("Enter a number to find its natural logarithm: ");
num = scanner.nextDouble();
naturalLogarithm(num);
break;
case 4:
System.out.print("Enter the base: ");
num = scanner.nextDouble();
System.out.print("Enter the exponent: ");
double exponent = scanner.nextDouble();
powerFunction(num, exponent);
break;
case 5:
running = false;
break;
default:
System.out.println("Invalid choice!");
break;
}
}
System.out.println("Exiting the calculator...");
scanner.close();
}
public static Double squareRoot(Double num) {
Double result = 0.0;
if (num < 0) {
System.out.println("Cannot calculate square root of a negative number.");
} else {
result = Math.sqrt(num);
System.out.println("Square root of " + num + " is " + result);
}
return result;
}
public static Double naturalLogarithm(Double num) {
Double result = 0.0;
if (num <= 0) {
System.out.println("Natural logarithm is not defined for non-positive numbers.");
} else if (num == 1) {
System.out.println("Natural logarithm of " + num + " is 0");
} else {
result = Math.log(num);
System.out.println("Natural logarithm of " + num + " is " + result);
}
return result;
}
public static Double powerFunction(Double num, Double exponent) {
double result = 0.0;
result = Math.pow(num, exponent);
System.out.println(num + " raised to the power of " + exponent + " is " + result);
return result;
}
public static int factorial(int n) {
if (n == 0)
return 1;
if (n < 0)
return -1;
return n * factorial(n - 1);
}
}