如何在Java中使用for循环对列中的平方、立方数值求和
核心问题
现有代码缺少存储平方、立方累加结果的变量,每次循环计算出的单值没有累计存储,同时for循环的变量声明逻辑冗余。
修正后代码
public class Main { public static void main(String[] args) { int squareSum = 0; int cubeSum = 0; System.out.println("\nNumber\tSquare\tCube\n"); for (int ctr = 1; ctr <= 5; ctr++){ int number = ctr * 2; int square = number * number; int cube = square * number; squareSum += square; cubeSum += cube; System.out.println(number + "\t" + square + "\t" + cube); } System.out.println("\nTotal\t" + squareSum + "\t" + cubeSum); } }
效果说明
运行后平方列总和为220,和示例要求的4+16+36+64+100 = 220结果完全匹配,立方列同步完成累加输出。
内容的提问来源于stack exchange,提问作者Klaus Hargreeves
相关产品推荐
相关产品推荐

