[英]How to create a recursive sum of squares method of n numbers?
My code must recive n numbers and return the sum of their squares in a recursive method. 我的代码必须接收n个数字,并以递归方法返回其平方和。
Ex: the sum of 1,1,2,2,3 squares must be 19 (1+1+4+4+9) 例如:1、2、2、3平方和必须为19(1 + 1 + 4 + 4 + 9)
My code is printing 14 for some reason. 由于某种原因,我的代码正在打印14。
import java.util.Scanner;
/**
*
* @author User
*/
public class SomaQuadrados {
/**
* @param args the command line arguments
*/
public static void main(String[] args)
{
Scanner teclado = new Scanner(System.in);
int n = teclado.nextInt();
int numero = 0;
for(int i = 0; i < n; i++)
{
numero = teclado.nextInt();
}
System.out.println(somaQuadrados(numero));
}
public static int somaQuadrados(int numero)
{
if(numero == 0)
{
return 0;
}
else
{
return somaQuadrados(numero-1) + (numero*numero);
}
}
}
The problem is your recursive function somaQuadrados()
should be processing the list [1, 1, 2, 2, 3]
of numbers. 问题在于您的递归函数
somaQuadrados()
应该正在处理数字的列表[1, 1, 2, 2, 3]
somaQuadrados()
[1, 1, 2, 2, 3]
。 That is: 那是:
<first number> * <first number> + somaQuadrados(<rest of numbers>)
with base case of an empty list. 与空列表的基本情况。 But instead you're taking an individual number and calculating:
但取而代之的是,您使用一个单独的数字并计算:
<number> * <number> + somaQuadrados(<number - 1>)
Which is a completely different program. 这是一个完全不同的程序。 When you process the final element
3
, you get 14
which is 1 * 1 + 2 * 2 + 3 * 3
. 处理最后一个元素
3
,得到14
,即1 * 1 + 2 * 2 + 3 * 3
。
I would expect a solution to this problem to look more like: 我希望该问题的解决方案更像是:
import java.util.*;
public class SomaQuadrados {
public static void main(String[] args)
{
List<Integer> numeros = new ArrayList<>();
Scanner teclado = new Scanner(System.in);
while (teclado.hasNextInt()) {
int numero = teclado.nextInt();
numeros.add(numero);
}
System.out.println(somaQuadrados(numeros));
}
public static int somaQuadrados(List<Integer> numeros)
{
int size = numeros.size();
if (size == 0)
{
return 0;
}
int numero = numeros.get(0);
return numero * numero + somaQuadrados(numeros.subList(1, size));
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.