用java实现以下场景,有100条商品,每个商品的价格0到1000元不等
商品数据:
{ id: 1, productName: '特价商品1', price: 200 }, { id: 2, productName: '特价商品2', price: 400 }, { id: 3, productName: '特价商品3', price: 600 }, { id: 4, productName: '特价商品4', price: 800 },
例如200元 加价之后就是240元 利润是40元
首先把0到300元的商品的加价30%,301到500的加价20%,501到1000元商品的加价10%,
然后0到300元的商品订单有300条,301-500的商品订单有400条,501-1000的商品订单有300条,
最后计算他的总利润有多少,最好写出算法
只计算总利润,那么关注每个元素的 price
即可。以下是一段伪代码示意:
CALC(A) R = 0 N = A.length for i in 0..N P = A[i].price if P <= 300 R += P * 0.3 else if P <= 500 R += P * 0.2 else R += P * 0.1 return R
若是计算的同时又需要修改,则可以加上这些:
CALC(A) R = 0 N = A.length for i in 0..N P = A[i].price if P <= 300 R += P * 0.3 + A[i].price *= 1.3 else if P <= 500 R += P * 0.2 + A[i].price *= 1.2 else R += P * 0.1 + A[i].price *= 1.1; return R
大概思路是,在 calculateTotalProfit 中,遍历所有商品,并根据价格范围确定对应的利润百分比(30%、20%、或10%)。然后,根据商品的价格和利润百分比计算单个商品的利润,并累加到 totalProfit 变量中。运行最后的时候,返回计算得到的总利润。代码比较简单,注释差不多都解释了,所以不做过多赘述。
import java.util.ArrayList; import java.util.List; class Product { int id; String productName; int price; public Product(int id, String productName, int price) { this.id = id; this.productName = productName; this.price = price; } } public class ProfitCalculator { public static void main(String[] args) { List<Product> products = new ArrayList<>(); // 添加100条商品数据 // 例如:products.add(new Product(1, "特价商品1", 200)); // products.add(new Product(2, "特价商品2", 400)); // ... int totalProfit = calculateTotalProfit(products); System.out.println("总利润为:" + totalProfit + "元"); } public static int calculateTotalProfit(List<Product> products) { int totalProfit = 0; for (Product product : products) { int price = product.price; int profitPercentage; // 根据价格范围确定利润百分比 if (price <= 300) { profitPercentage = 30; } else if (price <= 500) { profitPercentage = 20; } else { profitPercentage = 10; } // 计算单个商品的利润 int profit = price * profitPercentage / 100; totalProfit += profit; } return totalProfit; } }
回复