#35275: 注意!!! 只能使用+=


liaoweichen1024@gmail.com (M_SQRT)

學校 : 新北市立新莊高級中學
編號 : 195452
來源 : [210.71.71.201]
最後登入時間 :
2024-04-22 18:08:18
k570. pA. 關於友善時光這件事 -- 112學年度hgsh校內賽 | From: [118.166.136.101] | 發表日期 : 2023-05-21 03:30

這題有些測資「也許」是有爭議的,題主的解題報告中使用+=去結算總金額,但這題只能用+=,將浮點數取整再加總就錯了,舉個例子:
double d = 0.9_999_999_999_999_999;
System.out.println(d); //0.9999999999999999
System.out.println((int)d); //0
int x = 0;
System.out.println(x+=d); //0
x = 5;
System.out.println(x+=d); //6
 
在某些情況下,整數做+=不一定是加上後面那個數字取整的結果。
 
Java OOP寫法
這題我把主函式和物件寫在同一個類別裡,如果你正好在學物件的撰寫,提供給你參考:
public class k570 {
    //物件為超商
    //超商的折扣
    double off;
    //折扣的時段
    int[][] businessHours;
    
    //物件初始化
    k570(int[][] businessHours, double off) {
        this.businessHours = businessHours;
        this.off = off;
    }
    
    //類別(主)函式
    public static void main(String[] args) throws java.io.IOException {
        //宣告四間超商
        final int[] zero = {0, 1};
        k570[] market = {new k570(new int[][] {{1080, 1440}, zero}, 0.7),
                new k570(new int[][] {{600, 1440}, zero}, 0.7),
                new k570(new int[][] {{600, 1021}, {1200, 1440}, zero}, 0.65),
                new k570(new int[][] {{990, 1351}}, 0.6)};
        int i, t, m, ans=0;
        //輸入資料
        for(;;) {
            ans += market[i].getMoney(t, m);
        }
        //輸出ans
        
    }
    //物件函式
    //算出此時段的價格
    int getMoney(int time, int money) {
        for(int[] arr: businessHours)
            if(arr[0]<=time&&time<arr[1])
                return (int)(money*off);
        return money;
    }

}
因為上述提到的+=的問題,所以其實這裡不能直接使用getMoney函式,我的改法是將getMoney改成addMoney,並且將ans改成靜態的類別變數,具體怎麼寫就交給你思考囉~
 
希望這篇解題報告能幫助到你^_^
 
ZeroJudge Forum