程式控制結構
阿新 • • 發佈:2018-12-10
一.if語句
1.一個分支的if語句
形式:if(表示式) 語句:
2.if-else語句
形式:if(表示式)語句1;
else 語句2
3.if語句的巢狀
例(if-else):給定一個整數N,判斷其正負。
如果N > 0, 輸出positive;
如果N = 0, 輸出zero;
如果N < 0, 輸出negative
#include <iostream> using namespace std; int main() { int N; cin>>N; if (N>0) { cout<<"positive"; } else if(N==0) { cout<<"zero"; } else { cout<<"negative"; } return 0; }
例(if巢狀)
判斷某年是否是閏年
輸入只有一行,包含一個整數a(0 < a < 3000
輸出一行,如果公元a年是閏年輸出Y,否則輸出N
#include <iostream> using namespace std; int main() { int n; cin>>n; if (n%4==0) { if (n%100==0&&n%400!=0) cout <<"N"; else cout<<"Y"; } else cout<<"N"; return 0; }