我需要做这样的事情 - 用户输入一个数字(例如 5),程序显示以下操作的结果:1*1*1 + 2*2*2 + 3*3*3 + 4 *4*4 + 5*5*5。 我的代码如下:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter your number:");
int n = input.nextInt();
int a[] = new int[n];
int power = 0;
int sum = 0;
for (int i = 1; i <= a.length; i++)
{
power = (int) pow(i, 3);
// Maybe here'a the problem, a[n] has not enough space for the power (???)
sum += a[power];
}
System.out.println(Result: " + sum);
}
我认为我理解为什么这段代码不起作用,但我会感激任何关于如何正确执行和运行它的想法。
最佳答案
sum += power;
,不需要a
。
关于java - 如何用 3 的幂对数组内容求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20621402/