我想打印一个大小为n的数组,其中每个元素都是pow(i,i),i的范围从1到n。即,如果我输入 n = 4,它应该返回一个数组 A = {1, 4, 27, 256}。这是因为 power(1,1) = 1、power(2,2) = 4、power(3,3) = 27 和 power(4,4) = 256。
但是,当我尝试运行下面的代码时,它没有给出任何输出。
import java.io.*;
import java.util.*;
import java.lang.Math;
public class Main
{
public static void main(String[] args)
{
Main s = new Main();
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
double[] A = new double[n];
int j ;
for(j = 0; j <= n; j++)
{
A[j] = Math.pow(j+1, j+1);
//System.out.println(A[j]); --> 1
}
System.out.print(A);
System.out.println(A); //-->2
for (int i=0; i<A.length; i++)
{
System.out.print(A[i]+" "); // --> 3
}
}
}
当我尝试删除方程式 1 的注释引号时,它正在打印值。但等式 2 或 3 都无法帮助我打印数组。
最佳答案
试试这个:-
public static void main(String[] args) {
Main s = new Main();
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
double[] A = new double[n];
int j ;
for(j = 0; j <= n-1; j++)
{
A[j] = Math.pow(j+1, j+1);
//System.out.println(A[j]); --> 1
}
System.out.print(A);
System.out.println(A); //-->2
for (int i=0; i<A.length-1; i++)
{
System.out.print(A[i]+" "); // --> 3
}
}
关于java - Java 中未打印数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60681447/