gpt4 book ai didi

java - 如何使用嵌套循环分别输出整数的幂及其扩展形式

转载 作者:行者123 更新时间:2023-12-04 09:54:09 25 4
gpt4 key购买 nike

我想输出从 n (0) 到 n (10) 的功率表,只使用扫描仪输入基数。

目前,我在设置时遇到困难

代码:

else if (option == 2){
int base = keyboard.nextInt();
for (int x = base; x <= base; x++){
System.out.print(base+"^");
for (int y = 0; y <= 10; y++){ // "y" is exponent
System.out.print(y+"=");
}
System.out.println("");
}
}

样本输入:
  2
5

预期输出:
     5^0=
5^1=
5^2=
5^3=
- - - several lines are skipped here - - -
5^10=

注意:这不是预期的输出,但我想自己尝试代码这只是将我带到最终结果的步骤

最佳答案

您的代码中的问题:

  • 您已使用 result在循环内部,因此每次迭代都会重置。
  • 您已将打印语句放入循环
  • 你需要乘以resultbase每次迭代都没有完成。

  • 请按以下步骤操作:
    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();
    int exponent = keyboard.nextInt();
    int result = 1;
    if (option == 1) {
    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.print("=" + result);
    }
    }
    }
    }

    示例运行:
    1
    2
    5
    2^5=2*2*2*2*2=32

    [更新]

    根据您的评论,您还没有学会 ternary operator但我强烈建议你学习它。下面给出的解决方案是不使用三元运算符:
    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();
    int exponent = keyboard.nextInt();
    int result = 1;
    if (option == 1) {
    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++) {
    if (y < exponent) {
    System.out.print(base + "*");
    } else if (exponent != 1) {
    System.out.print(base);
    }
    result *= base;
    }
    System.out.print("=" + result);
    }
    }
    }
    }

    关于java - 如何使用嵌套循环分别输出整数的幂及其扩展形式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61960343/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com