Итак, в качестве мысленного упражнения я попытался написать очень простой калькулятор, который может выполнять такие функции, как сложение, вычитание, умножение, деление и вычисление степеней (и, в конечном итоге, корней), путем добавления или вычитания 1 с помощью циклов for. и вложенные для циклов.
Однако мне нужна помощь с функцией мощности (последний метод в коде ниже). Поскольку для умножения требуется один вложенный цикл for (третий метод, показанный ниже), я полагал, что функция степени будет просто еще на один или два уровня глубже. Но либо это не так, либо я неправильно кодирую, что, как я полагаю, более вероятно из двух.
import java.util.*;
public class Main {
public static Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
Power();
}
public static void addition() {
System.out.println("Type first number to add: ");
int num1 = scan.nextInt();
System.out.println("Type second number to add");
int num2 = scan.nextInt();
int result = num1;
while(num2 > 0){
num2--;
result++;
}
System.out.println("The result is: " + result);
}
public static void subtraction() {
System.out.println("Type first number to subtract: ");
int num1 = scan.nextInt();
System.out.println("Type second number to subtract: ");
int num2 = scan.nextInt();
int result = num1;
while(num2 > 0){
num2--;
result--;
}
System.out.println("The result is: " + result);
}
public static void multiplication() {
System.out.println("Type first number to multiply: ");
int num1 = scan.nextInt();
System.out.println("Type second number to multiply: ");
int num2 = scan.nextInt();
int result = 0;
for(int i = num1;i>0;i--){
for(int x = num2;x>0;x--){
result++;
}
}
System.out.println("The result is: " + result);
}
public static void division() {
System.out.println("Type first number to divide: ");
int num1 = scan.nextInt();
System.out.println("Type second number to divide: ");
int num2 = scan.nextInt();
int result = 0;
for(;num2>0 && num1 > num2;num2--){
result++;
for(;num1 > num2;num1--){
}
}
System.out.println("The result is: " + result);
}
public static void Power() {
System.out.println("Type Base Number: ");
int num1 = scan.nextInt();
System.out.println("Type Exponent: ");
int num2 = scan.nextInt();
int result = 0;
for(int i = num1;i>0;i--){
for(int x = num1;x>0;x--){
for(int y = num2; y>0; y--){
for(int z = num2; z>0;z--){
result++;
}
}
}
}
System.out.println("The result is: " + result);
}
}