--- tags: Cmoney_Java題目 --- Java_Cmoney_ft7207 ===   1.主程式 --- 這題麻煩的在於要把變數邏輯分開,避免加來減去,難以理解,也難以debug 1. 除了題目要求的總花費、總存款和存款目標,薪水要獨立一個變數 因為有獎金和加薪兩種存款變多的方式,所以獨立出來處理 2. 熟悉的 while 迴圈 搭配輸入 -1 結束 1. 如果 -1 跳出 2. 每三個月發獎金,直接加進存款變數 3. 每六個月加薪,更改薪水變數 4. 每月薪水進存款 5. 計算總花費 6. 當存款達到目標將完成的月數紀錄到 goalmonth, ==特別注意`&& goalmonth == 0`==,達到存款的那個月之後, 每個月都會達到目標,所以要確保是達到存款目標的第一次 7. count++ 前往下個月 3. 輸出總花費、總存款 4. 如果 goalmonth = 0 就代表沒完成,否則就印出 goalmonth ```java= import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int sal = sc.nextInt(); int goal = sc.nextInt(); int goalmonth = 0; int costs = 0; int count = 1; int safe = 0; while (true) { int cost = sc.nextInt(); if (cost == -1) break; if (count % 3 == 0) safe += 5000; if (count % 6 == 0) sal += 5000; safe += sal; costs += cost; if ((safe - costs) >= goal && goalmonth == 0) goalmonth = count; count++; } System.out.println(costs); System.out.println(safe-costs); if(goalmonth == 0) System.out.println(-1); else System.out.println(goalmonth); } } ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up