#独家
用Java实现以下问题 最好用算法来实现?

2023-08-05 0 1,201

用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;
    }
}

回复

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

1. JK下载官网所有资源来源于开发团队,加入会员即可下载使用!如有问题请联系右下角在线客服!
2. JK下载官方保障所有软件都通过人工亲测,为每位会员用户提供安全可靠的应用软件、游戏资源下载及程序开发服务。
3. JK开发团队针对会员诉求,历经多年拥有现今开发成果, 每款应用程序上线前都经过人工测试无误后提供安装使用,只为会员提供安全原创的应用。
4. PC/移动端应用下载后如遇安装使用问题请联系右下角在线客服或提交工单,一对一指导解决疑难。

JK软件下载官网 技术分享 用Java实现以下问题 最好用算法来实现? https://www.jkxiazai.com/2393.html

JK软件应用商店是经过官方安全认证,保障正版软件平台

相关资源

官方客服团队

为您解决烦忧 - 24小时在线 专业服务