我有以下任務,撰寫一個獲取價格串列并將其匯總的方法,僅包括大于 minPrice(含)和小于 maxPrice(含)的價格,并回傳金額。
只能使用 for 回圈。
我有一個錯誤的結果作為回報。
我認為 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。我想它只計算陣列的前四個索引。
uj5u.com熱心網友回復:
為什么要增加一個計數器?您剛剛獲得了正確元素的 NUMBER 個,但是您從第一個 (0) 個元素開始迭代。相反,您可以在第一個 foo 回圈中總結它,如下所示:
for(int i = 0; i < prices.length; i ) {
int price = prices[i];
if (price >= minPrice && price <= maxPrice) newResult = price;
}
uj5u.com熱心網友回復:
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;
}
uj5u.com熱心網友回復:
計算 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));
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/465266.html
