如何使我的答案在Java中正确打印

问题描述 投票:0回答:2

我遇到一个问题,当我的程序打印(base)^0=时,它不打印答案(1)(我总结了输出示例,因为我只对输出的第一行有问题)

预期输出:

2^0=1
2^1=2
2^2=2*2=4
2^3=2*2*2=8
2^4=2*2*2*2=16

实际输出:

> 2^0=
> 2^1=2=2
> 2^2=2*2=4
> 2^3=2*2*2=8
> 2^4=2*2*2*2=16

代码:

else if(option == 2){
        base = Input.nextInt();

        for(int i = 0; i<10; i+=1){
            System.out.print(base+"^"+i+"=");
            for(int j = 0; j < i; j+=1){
                 if(j != i -1){
                System.out.print(base+"*");
                }else{

                        System.out.format(base+"="+"%.0f",Math.pow(base,i));

                }

            }

            System.out.println("");
        }

    }
java math exponent
2个回答
1
投票

i = 0时的第一轮,您不输入内部for循环,因为要输入的条件是j < i,即0 < 0 => false


0
投票

执行以下操作:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        int option = keyboard.nextInt();
        int base = keyboard.nextInt();
        if (option == 2) {
            for (int exponent = 0; exponent <= 10; exponent++) {
                int result = 1;// Reset `result` to `1` with each iteration
                for (int x = base; x <= base; x++) {
                    if (exponent <= 1) {
                        System.out.print(base + "^" + exponent);
                    } else {
                        System.out.print(base + "^" + exponent + "=");
                    }
                    for (int y = 1; y <= exponent; y++) {
                        System.out.print(exponent == 1 ? "" : (base + (y < exponent ? "*" : "")));
                        result *= base;
                    }
                    System.out.println("=" + result);
                }
            }
        }
    }
}

示例运行:

2
2
2^0=1
2^1=2
2^2=2*2=4
2^3=2*2*2=8
2^4=2*2*2*2=16
2^5=2*2*2*2*2=32
2^6=2*2*2*2*2*2=64
2^7=2*2*2*2*2*2*2=128
2^8=2*2*2*2*2*2*2*2=256
2^9=2*2*2*2*2*2*2*2*2=512
2^10=2*2*2*2*2*2*2*2*2*2=1024
© www.soinside.com 2019 - 2024. All rights reserved.