找出从1到N的数字的平方和? (没有以前的金额)

时间:2018-10-25 04:39:51

标签: java

我编写的程序的左边有一个从5到49的奇数列表,而右边的列则是从1到N的平方和(左边的数字)。我的代码的问题是它加上了之前的总和。例如:

5 || 55

7 || 195

9 || 480

    int s, n, sumsq;
    sumsq = 0;

    for (n = 5; n <= 49; n+= 2) {
        for(s=1; s <= n; s++)
            sumsq += (s*s);
        System.out.println(n+"\t"+sumsq);  

3 个答案:

答案 0 :(得分:1)

在您的第一个for循环中将sumsq重置为0,这样就不会累积值。

int s, n, sumsq;


    for (n = 5; n <= 49; n+= 2) {
        sumsq = 0;
        for(s=1; s <= n; s++)
            sumsq += (s*s);
        System.out.println(n+"\t"+sumsq);  

答案 1 :(得分:0)

更改为:

int s, n, sumsq;
sumsq = 0;

for (n = 5; n <= 49; n+= 2) {
               sumsq = 0;
    for(s=1; s <= n; s++){
        sumsq += (s*s);
    }
    System.out.println(n+"\t"+sumsq);  
}

重置总和。

答案 2 :(得分:0)

只是为了好玩,这是Java 8的实现方式:-

IntStream.rangeClosed(5, 49)
        .filter(i -> i % 2 != 0)
        .boxed()
        .collect(Collectors.toMap(
                Function.identity(),
                i -> IntStream.rangeClosed(1, i)
                        .map(operand -> operand * operand)
                        .sum(),
                (u, v) -> null,        //if order of result doesn't matter, get rid of this
                LinkedHashMap::new))   //and this line
        .entrySet()
        .forEach(System.out::println);