--- tags: 解題報告,zj --- # a004. 文文的求婚 ###### tags: 流程控制、數學 題目連結: [Zerojudge](https://zerojudge.tw/ShowProblem?problemid=a004) ## 題目說明 持續輸入`int`直到`EOF(End of file)`分辨平年閏年 ## 想法 1. `EOF`處理 2. 閏年規則: 1. 能被400整除 2. 被4整除且不能被100整除 ## 參考答案 :::spoiler 點我展開 Runtime: 8ms Memory: 308KB 時間複雜度:$O(N)$ 空間複雜度:$O(1)$ ```cpp= #include<iostream> using namespace std; int main(){ int year; while (cin>>year){ if ( year%400==0 or ( year%4==0 and year%100!=0 ) ) cout<<"閏年"<<endl; else cout<<"平年"<<endl; } } ``` [Github](https://github.com/henryleecode23/solve_record/tree/main/zerojudge/a004) ::: ## 解釋 ### EOF處理 ```cpp=5 while (cin>>year) ``` ### 閏年判斷 閏年的兩個條件==只要其中一個成立==即為閏年, 因此判斷方式應使用`or`做判斷 條件2中, 要求能被4整除==且==不被100整除所以應使用`and`做判斷 要判斷是否被整除使用模運算(`%`) ```cpp= if ( year%400==0 or ( year%4==0 and year%100!=0 ) ) cout<<"閏年"<<endl; else cout<<"平年"<<endl; ``` ## 其他語言解法 :::spoiler Python ```python= while True: try: year = int(input()) print("閏年" if (((year%4)==0) and ((year%100)!=0) or ((year%400) ==0)) else "平年") except EOFError: break ``` ::: ## 心得 這題應該是ZJ上第一個會遇到`EOF`的題目如果是初學可能不知道該如何處理
×
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