So just as a thought exercise, I've been trying to code a very simple calculator that can perform functions such as addition, subtraction, multiplication, division, and powers (and eventually roots) by adding or subtracting 1 through the use of for loops and nested for loops.
I need help however with the power function(last method in code below). As multiplication requires a single nested for loop (third method shown below), i figured the power function would just be another level or two deeper. But either that is not the case, or I am not coding properly, which is the more likely of the two I suppose.
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);
}
}
答案 0 :(得分:0)
你可以这样做。这有点模块化,但如果你想在一个完整的循环中,你可以将乘法函数中的代码放入幂函数。
for loop --> hello() --> getJson's inner function
组合:
let