计算范围内包含的数组价格总和

Calculate sum of array's prices included within range

我有以下任务,编写一个方法,获取价格列表并将它们相加,仅包括那些大于 minPrice(含)和小于 maxPrice(含)的价格,以及 return数量。

只能使用for循环

我在 return 中得到了错误的结果。

我假设我在 if (price >= minPrice && price <= maxPrice) counter++;

中有错误

但是我不明白为什么。

    public int getPricesSum(int[] prices, int minPrice, int maxPrice) {
        
        if (prices.length == 0) return 0;
        
        int counter = 0;
        
        for(int i = 0; i < prices.length; i++) {
            int price = prices[i];
            if (price >= minPrice && price <= maxPrice) counter++;
        }
        
        int result [] = new int [counter];
        
        int newResult = 0;
        
        for(int i = 0; i < result.length; i++) {
            newResult += prices[i];
        }
        
        return newResult;
        
    }

    public static void main(String[] args) {
        QuadraticEquationSolver shop = new QuadraticEquationSolver();

        //Should be 144 - 20 + 50 + 40 + 34
        int[] prices = new int[] {10, 20, 50, 40, 34, 500};
        System.out.println(shop.getPricesSum(prices, 20, 50));
    }
  }

结果是120。 我想它只计算数组的前四个索引。

为什么要递增计数器?您刚刚获得了 NUMBER 个正确的元素,但随后您从第一个 (0) 个元素开始迭代。相反,您可以像这样在第一个 foor 循环中总结它:

for(int i = 0; i < prices.length; i++) {
    int price = prices[i];
    if (price >= minPrice && price <= maxPrice) newResult += price;
}

您计算 minPrice 和 maxPrice 内的价格数量的第一位根本没有用。另外,声明第二个数组的大小与您范围内包含的价格数量并没有帮助您计算价格总和。

现在,您只需确定您范围内的价格总和。计数不是您目标的一部分,也不会帮助您实现目标。在开始编写代码之前,请始终考虑实现目标所需采取的步骤。

我想这就是你想要做的:

public int getPricesSum(int[] prices, int minPrice, int maxPrice) {
    int newResult = 0;    
    for(int i = 0; i < prices.length; i++) {
        if (prices[i] >= minPrice && prices[i] <= maxPrice){
            newResult += prices[i];
        }
    }
    return newResult;
}

public static void main(String[] args) {
    QuadraticEquationSolver shop = new QuadraticEquationSolver();

    //Should be 144 - 20 + 50 + 40 + 34
    int[] prices = new int[] {10, 20, 50, 40, 34, 500};
    System.out.println(shop.getPricesSum(prices, 20, 50));
}
public int getPricesSum(int[] prices, int minPrice, int maxPrice) {
    int sum = 0;
    for (int price : prices) {
        if (price >= minPrice && price <= maxPrice) {
            sum += price;
        }
    }
    return sum;
}