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



我想将功率表从 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=

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

代码中的问题:

  1. 您在循环中使用了result,因此每次迭代都会重置它。
  2. 您已将 print 语句放入循环中
  3. 您需要在每次未完成的迭代中将result乘以base

按如下方式操作:

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

[更新]

根据您的评论,您还没有学习三元运算符,但我强烈建议您学习它。下面给出的解决方案不使用三元运算符:

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);
}
}
}
}

最新更新