java如何打印一组数字以及从1到列表中每个数字的平方和?
我如何用两种不同的方法编写这个问题?我知道这可以在一个循环和一个嵌套循环中完成,但它需要这样做。我知道这都错了,但我需要帮助理解逻辑
public static int numloop(int n){
int nd = 0;
for(n = 5; n <= 49; n += 2){
nd = ndiv(n);
}
return nd;
}
public static int ndiv(int numb){
int sumsq = 0;
for( int x = 1; x <= numb; x++ ){
sumsq += x * x;
}
return sumsq;
}
public static void main(String[]args){
System.out.println("NUMBER\t" + "SUMSQ");
System.out.println(n + nd);
}
输出应该如下所示:
数| |平方和
5 | | 55
7 | | 140
9 | | 285
# 1 楼答案
Tony-无法准确地计算出您想要的代码,所以我冒昧地让它更灵活一些。你应该很容易限制它只做你想做的事
输出:
# 2 楼答案
这很简单@Tony。如果您希望使用两种方法完成此操作,则只需按如下方式将其拆分:
以下是该项目流程的概述:
i
值调用Square()
方法。同时计算总和李>我已将代码及其输出附在下面:
代码:
输出: